I am currently working with a setup that involves defining interfaces for animals and their noises, along with classes for specific animals like dogs and cats. I am also storing these animals in an array named pets.
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;
}
}
const pets: Animal<any>[] = [new Cat(), new Dog()];
for (const pet of pets) {
console.log(pet.makeNoise());
}
I need to figure out the best type definition for animals
so that pet.makeNoise()
returns the correct type. Is using an array the most efficient way to store these animals, or is there another approach I should consider? Any guidance on this matter would be greatly appreciated!