[英]Typescript type check for an array with mixed types and mixed generics
我有以下設置
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
,或者這種解決問題的方法不是最好的? 謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.