访问并非所有类型上都存在的联合类型的属性的正确方法是什么?我似乎总是得到一个打字稿";所有物类型上不存在"错误,即使我检查以确保属性存在(见下面的例子(
interface Car {
wheels: 4,
spareWheels: 1,
}
interface Bicycle {
wheels: 2,
}
type Vehicle = Car | Bicycle
getWheelCount(vehicle: Vehicle): number => {
return vehicle.spareWheels ? vehicle.spareWheels + vehicle.wheels : vehicle.wheels
}
文件(https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types(有一个使用"typeof"的解决方案,但这对自定义类型不起作用。
您可以像这样使用in
运算符:
interface Car {
wheels: 4;
spareWheels: 1;
}
interface Bicycle {
wheels: 2;
}
type Vehicle = Car | Bicycle;
const getWheelCount = (vehicle: Vehicle): number => {
return "spareWheels" in vehicle // using `in` operator
? vehicle.spareWheels + vehicle.wheels
: vehicle.wheels;
};
您可以使用类型谓词。
interface Car {
wheels: 4;
spareWheels: 1;
}
interface Bicycle {
wheels: 2;
}
type Vehicle = Car | Bicycle;
const getWheelCount = (vehicle: Vehicle): number => {
return isVehiculeCar(vehicle) ? vehicle.spareWheels + vehicle.wheels : vehicle.wheels;
};
const isVehiculeCar = (subject: Vehicle): subject is Car => {
return (subject as Car).spareWheels !== undefined;
};
通过这种方式,Typescript将知道您处理的是Car
还是Bicycle
。
从技术上讲,Typescript是在函数isVehiculeCar
之后用Car
类型来推断vehicule
var。这意味着,如果您使用具有智能键入功能(如自动完成(的IDE,则只能访问此范围内的Car
接口属性。