【发布时间】:2021-04-26 14:49:51
【问题描述】:
假设我有返回动物信息的 API。但是,对于每种动物,json 有效负载差异很大,即使许多属性是常见的和强制性的。
我想为这些不同的动物中的每一种设置“强类型”打字稿类,这样我的代码就不会变得一团糟。每种动物都需要非常独特和特定的处理方式!
这样做的正确方法是什么?基本上我想完成这样的事情:
interface Animal {
Name: string;
Weight: number;
}
interface Insect extends Animal {
AmountOfEyes: number;
}
interface Bird extends Animal {
PlumageColor : string;
}
function OnlyForBirds(bird: Bird)
{
// do something birdly
}
function OnlyForInsects(insect: Insect)
{
// do something creepy
}
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
}
function ProcessAnimal(animalId:string) : Promise
{
let animal = await GetAnimal(animalId);
// how do I do this now? Can't I use something over tye interface
// types instead of using the .Name and casting again?
// is there any advisable standard I can use?
if(animal is a bird){
OnlyForBirds(bird)
}
else if(animal is an insect){
OnlyForInsects(insect)
}
}
感谢您提出任何建议,包括不使用此类界面。
【问题讨论】:
标签: typescript typescript-generics react-typescript