0

I have the following setup

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());
}

How can I write a type definition for animals such that pet.makeNoise() returns the right type? Could this perhaps be achieved by using something other than an array to store animals, or maybe this approach to solving the problem is not the best? Thanks!

1 Answers1

0

You should use union type as in the following post

In your case :

Animal<CatNoise|DogNoise>

Jérôme
  • 56
  • 1
  • 5