Imagine I have different APIs that provide data about various animals. Despite some shared properties, the JSON payloads for each animal type are quite unique and specific.
To avoid chaos in my code, I am looking to create strongly typed TypeScript classes for each distinct animal type. Each animal requires its own specialized handling!
What would be the most effective approach to achieve this? Ideally, I aim to implement something along these lines:
interface Animal {
Name: string;
Weight: number;
}
interface Insect extends Animal {
AmountOfEyes: number;
}
interface Bird extends Animal {
PlumageColor : string;
}
function OnlyForBirds(bird: Bird)
{
// perform bird-related actions
}
function OnlyForInsects(insect: Insect)
{
// do something insect-like
}
function GetAnimal(animalId: string) : Promise<Animal>
{
const uri = `${baseURL}/${animalId}`;
// fetches the json response body from http request
const result = await get<any>(uri);
switch(animal.Name)
{
case 'Insect':
return result as Insect;
case ...
...
}
// throw unhandled error
}
function ProcessAnimal(animalId:string) : Promise
{
let animal = await GetAnimal(animalId);
// how can I handle this now? Can't I make use of a more convenient method over tye interfaces
// rather than relying on .Name and re-casting?
// Is there an industry standard I should follow?
if(animal is a bird){
OnlyForBirds(bird)
}
else if(animal is an insect){
OnlyForInsects(insect)
}
}
I welcome any suggestions, even those that steer away from using interfaces in this manner.