Typescript 更改变量';用打字机打字
这是我的问题,假设我有几种动物:Typescript 更改变量';用打字机打字,typescript,Typescript,这是我的问题,假设我有几种动物: interface IAnimal { type: string; legs: number; } interface IChicken extends IAnimal { eggsPerDay: number; } interface ICow extends IAnimal { milkProduction: number; } ... doSomethingWithAnimal(animal: IChicken|ICow):
interface IAnimal {
type: string;
legs: number;
}
interface IChicken extends IAnimal {
eggsPerDay: number;
}
interface ICow extends IAnimal {
milkProduction: number;
}
...
doSomethingWithAnimal(animal: IChicken|ICow): void {
switch(animal.type){
case 'cow':
alert(`the milk production is ${animal.milkProduction}`);
}
}
我的问题是typescript不知道是牛还是鸡。有没有一种方法,一旦我确定该动物属于ICow类型,我就可以安全地访问这些附加属性
我知道可以像ICow一样执行
const cow=animal
,但这不会不必要地复制我的变量吗?我提供的示例过于简单,因为我实际要解决的问题有十个派生类,并且函数名为“一吨”,因此我希望尽可能保持它的效率。您可以在该任务中使用有区别的并集。您只需将type
成员添加到union的每个memebr中,实际类型为字符串文本类型:
interface IAnimal {
type: string;
legs: number;
}
interface IChicken extends IAnimal {
type: "chicken";
eggsPerDay: number;
}
interface ICow extends IAnimal {
type: "cow";
milkProduction: number;
}
function doSomethingWithAnimal(animal: IChicken | ICow): void {
switch (animal.type) {
case 'cow':
alert(`the milk production is ${animal.milkProduction}`); // ok now
}
}
你可以在下面试试
doSomethingWithAnimal(animal: IChicken | ICow): void {
if(animal.hasOwnProperty('eggsPerDay')) {
console.log('eggsPerDay', animal.eggsPerDay)
} else if (animal.hasOwnProperty('milkProduction')) {
console.log('milkProduction', animal.milkProduction)
}; // other conditions
}
参考代码我建议在中使用一个
,它也可以充当TS类型的守卫:我认为@TitianCernicova Dragomir的答案更接近我的想法,因为animal.eggsPerDay仍然会导致错误。@SethKillian,没问题。但是你说的animal.eggsPerDay是什么意思呢?它仍然会导致en错误,一个打字错误hasOwnProperty
不会缩小参数的类型。这就是为什么我建议在
表达式中使用