我尝试使用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()
方法应返回正确的类型;
答案 0 :(得分:1)
insert(value: any)
函数应返回类型INode
。然后,特定的实现可以返回Node
或新的DerivedNode
,它们都可以分配给INode
。