【问题标题】:What type should the method return?该方法应该返回什么类型?
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 嗯,好的,我明白了,非常感谢。但是我还有其他麻烦:实现 INode 接口的类对象与 INode 不可比:javascript interface INode { copy(node: INode): void; } class Node implements INode { ... copy(node: Node) { ... } // Property 'node' in type 'Node' is not assignable to the same property in base type 'INode' } 为什么? Node 实现接口,是窄子类型
    • 我遇到了一个问题:insert(value: any): INode { return this; } 类型“this”不可分配给类型“INode”
    猜你喜欢
    • 2013-08-12
    • 2020-12-31
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    相关资源
    最近更新 更多