如何解决Typescript接口继承和泛型类型推断
我对TypeScript接口,泛型,类有一个小问题……不确定其中的哪一个,或者我的头被思考所淹没,我看不到简单的解决方案。 这是我的问题: 假设我具有以下接口:
interface Animal {
legs: number;
}
interface Cat extends Animal {
meouw : string;
}
interface Dog extends Animal {
waf : stringl
}
我希望能够做这样的事情:
interface GenericAnimal { specimen : <T extends Animal> } ;
let someAnimals : GenericAnimal[] = [
{ specimen : {legs : 3,meouw : 'mrrrr'} },{ specimen : {legs : 1,waf : 'hrrr' }
];
,这样GenericAnimal接口只能有“标本”来扩展Animal接口,但是在初始化GenericAnimal实例时,我将能够通过Intellisense访问扩展接口的属性。
请注意,使用GenericAnimal<T>
不是我的解决方案,因为我的someAnimals数组将需要容纳不同的“动物”(假设我有100多个)……。使用联合类型也可能不是一个好的解决方案。你有什么建议?
还有什么办法可以在销毁数组的每个项目(或遍历数组成员)之后推断出数组的每个项目的类型?Ty
解决方法
如果您不想使用discriminating union,则可以使用typeguards:
interface Animal {
legs: number;
}
function isAnimal(potentialAnimal: any): potentialAnimal is Animal {
return typeof potentialAnimal === "object" && "legs" in potentialAnimal && typeof potentialAnimal.legs === "number";
}
interface Cat extends Animal {
meouw: string;
}
function isCat(potentialCat: any): potentialCat is Cat {
return isAnimal(potentialCat) && "meouw" in potentialCat && typeof (potentialCat as Cat).meouw === "string"
}
interface Dog extends Animal {
waf: string;
}
function isDog(potentialDog: any): potentialDog is Dog {
return isAnimal(potentialDog) && "waf" in potentialDog && typeof (potentialDog as Dog).waf === "string"
}
interface GenericAnimal<T extends Animal = Animal> {
specimen: T
& Record<string,any> // Needed to stop extraneous prop check
};
let someAnimals: GenericAnimal[] = [
{
specimen: {
legs: 3,meouw: 'mrrrr'
}
},{
specimen: {
legs: 1,waf: 'hrrr'
}
}
];
someAnimals.map((genericAnimal: GenericAnimal): Animal => {
return genericAnimal.specimen;
}).forEach(animal =>{
if(isCat(animal)){
console.log(animal.meouw);
} else if(isDog(animal)) {
console.log(animal.waf);
}
});
if(isCat(someAnimals[0].specimen)) {
console.log(someAnimals[0].specimen.meouw);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。