【发布时间】:2020-10-23 19:35:33
【问题描述】:
我尝试使用 TypeScript,但我有点困惑。
我有接口:
interface INode {
parent: INode | null;
child: INode | null;
value: any;
insert(value: any): this; // (or INode or i don't know)
}
以及实现这个接口的类:
class Node implements INode {
left: INode | null;
right: INode | null;
constructor(public value: any, public parent: INode | null = null) {}
insert(value: any): this { // Type 'Node' is not assignable to type 'this'.
if(value == this.value) {
return this;
}
return new (<typeof Node>this.constructor)(value, this);// i've find this way in google
}
}
insert() 应该返回什么类型?
我试过了:
insert(value: any): this {
if(value == this.value) {
return this;
}
return new (<typeof Node>this.constructor)(value, this) as this;
}
但它看起来很奇怪而且有点不对;
Node 类将被扩展,insert() 方法应返回正确的类型;
【问题讨论】:
标签: typescript