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);
}

Playground

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...