首页 > 解决方案 > 该方法应该返回什么类型?

问题描述

我尝试使用 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

解决方案


insert(value: any)函数应返回类型INode。然后,特定的实现可以返回Node或一个新的DerivedNode,它们都可以分配给INode.


推荐阅读