javascript - 如何允许使用 Typescript 覆盖类方法?

标签 javascript typescript class

我有一个带有一些方法的 Animal 类,以及该类的一个扩展 - 称为 Bird - 覆盖其父方法之一以处理边缘情况。

看起来像这样:

class Animal {
  constructor(animal) {
    this.animal = animal;
  }
  public define(){
    return {name: this.animal.name}
  }
}

class Bird extends Animal{
  public define(){
    return {color: this.animal.color}
  }
}

调用bird.define()工作正常。但 Typescript 发疯了,声称:

Property 'define' in type 'Bird' is not assignable to the same property in base type 'Animal'. Type '() => { color: string; }' is not assignable to type '() => { name: string }'. Type '{ color: string; }' is missing the following properties from type '{ name: string; }':
name

除了执行 ts-ignore 之外,如何解决此问题?

最佳答案

这里有一个解决方法:


type AnimalObj = {
    name: string;
    color: string
}
class Animal {
    constructor(public animal: AnimalObj) {
        this.animal = animal;
    }
    public define(): Partial<AnimalObj> {
        return { name: this.animal.name }
    }
}

class Bird extends Animal {
    public define() {
        return { color: this.animal.color }
    }
}

在这种特殊情况下不需要使用ts-ignore

关于javascript - 如何允许使用 Typescript 覆盖类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66584925/

相关文章:

javascript - 滚动时 Angular 5 粘性菜单

javascript - 解决按钮点击太快的最佳常用方法是什么?

angular - 如何对 *ngFor 应用过滤器?

c++ - 指向类方法的指针

C++ - 成员初始化和递增的顺序

javascript - 使在 IFRAME 中加载的页面访问包含页面脚本的 JavaScript 对象

javascript - jQuery setinterval 不显示第一个元素

typescript - TypeError : L. Control.Draw 不是构造函数

html - Angular4+ 在 HTML 模板中显示/隐藏子元素

Javascript "classes"(无框架)