【发布时间】:2021-12-15 20:21:46
【问题描述】:
我有以下设置
interface Animal<T> {
name: string;
makeNoise: () => T;
}
enum DogNoise {
'bark',
}
class Dog implements Animal<DogNoise> {
name: 'goodboy';
makeNoise() {
return DogNoise.bark;
}
}
enum CatNoise {
'meow',
'purr',
}
class Cat implements Animal<CatNoise> {
name: 'needy';
makeNoise() {
return CatNoise.meow;
}
}
// what is the correct way to define generic for a mixed array
// knowing that other types of animals could be used (e.g. Cow) is using array the best approach to store them
const pets: Animal<any>[] = [new Cat(), new Dog()];
for (const pet of pets) {
// now makeNoise returns any
console.log(pet.makeNoise());
}
如何为animals 编写类型定义,使pet.makeNoise() 返回正确的类型?
这是否可以通过使用数组以外的东西来存储animals 来实现,或者这种解决问题的方法可能不是最好的?
谢谢!
【问题讨论】:
标签: typescript typescript-typings