网站搜索

javascript - 如何使用 Typescript 允许类方法被重写?


我有一个类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 会报错,声称:

类型 'Bird' 中的属性 'define' 不能分配给基类型 'Animal' 中的同一属性。类型 '() => { color: string; }' 不能分配给类型 '() => { name: string }'。类型 '{ color: string; }' 缺少类型 '{ name: string; }' 中的以下属性:
name

除了使用 ts-ignore,如何修复这个问题?

答案#1

这里有一个解决方法:

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