vscode intellisense在Typescript可链接方法中失败,返回“实例或数字”,如何解决?

问题描述 投票:0回答:1

请考虑以下代码:

class BaseType {
    private _group: any = {};
    private _a: number;
    constructor() { }

    group(g?: any): this | any {
        if (!g) {
            return this._group;
        }
        this._group = g;
        return this;
    }

    another(a?: number): this | number {
        if (Number(a) === +a) {
            this._a = a;
            return this;
        }
        return this._a;
    }
}

class Another {
    constructor() { }
    checkChainable() {
        const inst = new BaseType().group({ name: 'test' }).another(20); //The intellisense is not working here
    }
}

我唯一能解决VSCode中语法错误的原因是将返回类型更改为this | any

有什么可以解决VSCode intellisense问题和编译时错误的原因吗?

visual-studio-code typescript2.0
1个回答
1
投票

这是由联合类型的工作原理引起的。

对于another,结果类型是thisnumber,因此您只能在结果上使用这两种类型之间通用的属性/方法。如果要使用特定于BaseType的属性,则必须进行强制转换或类型检查:

const x = new BaseType().another(10)
const y = typeof x === 'number' ? x : x.another(20)

你没有在group案例中得到错误,因为你正在返回基本上减少到this | anyany,因为any允许访问任何属性或方法。但是出于同样的原因,你不会得到良好的智能感知

© www.soinside.com 2019 - 2024. All rights reserved.