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 Answer 1

0

You should use union type as in the following post

In your case :

Animal<CatNoise|DogNoise>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.