我应该如何访问typscript中联合类型的属性



访问并非所有类型上都存在的联合类型的属性的正确方法是什么?我似乎总是得到一个打字稿";所有物类型上不存在"错误,即使我检查以确保属性存在(见下面的例子(

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类型来推断vehiculevar。这意味着,如果您使用具有智能键入功能(如自动完成(的IDE,则只能访问此范围内的Car接口属性。

最新更新