请考虑以下代码:
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智能感知问题和编译时错误吗?
这是由联合类型的工作方式引起的。
对于another
,结果类型要么是this
要么是number
,所以你只能对结果使用这两种类型之间通用的属性/方法。如果要使用特定于BaseType
的属性,则必须进行强制转换或类型检查:
const x = new BaseType().another(10)
const y = typeof x === 'number' ? x : x.another(20)
在group
情况下,您不会收到错误,因为您返回的是this | any
,这基本上减少到any
,因为any
允许访问任何属性或方法。但是,出于同样的原因,您不会获得良好的智能感知