我有一个带有一些方法的 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/