簡體   English   中英

具有混合類型和混合泛型的數組的打字稿類型檢查

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM