I'm facing a dilemma with TypeScript interfaces, generics, classes... not exactly sure which one is causing the issue. My mind is in overdrive trying to find a solution but I can't seem to simplify things. Here's what I'm grappling with : Let's say I have the following interfaces :
interface Animal {
legs: number;
}
interface Cat extends Animal {
meouw : string;
}
interface Dog extends Animal {
waf : stringl
}
I want to achieve something like this :
interface GenericAnimal { specimen : <T extends Animal> } ;
let someAnimals : GenericAnimal[] = [
{ specimen : {legs : 3, meouw : 'mrrrr'} } ,
{ specimen : {legs : 1, waf : 'hrrr' }
];
The goal is for the GenericAnimal interface to only accept 'specimen'-s that extend the Animal interface. However, when initializing a GenericAnimal instance, I should be able to access the properties of the extending interfaces through Intellisense.
I've ruled out using GenericAnimal<T>
because my someAnimals array would need to accommodate various 'animals' (let's say there are more than 100). Using a union type may also not be the best solution. Any suggestions?
Also, is there a way to infer the type of each item in the array after destructuring it (or iterating through its members)? Thanks.