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