【问题标题】:Typescript type check for an array with mixed types and mixed genericsTypescript 类型检查具有混合类型和混合泛型的数组
【发布时间】: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


    【解决方案1】:

    您应该使用联合类型,如以下post

    在你的情况下:

    动物

    【讨论】:

      猜你喜欢
      • 2015-11-04
      • 2022-10-12
      • 1970-01-01
      • 2011-11-04
      • 1970-01-01
      • 2014-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多