【发布时间】:2020-03-24 18:10:50
【问题描述】:
在这个例子中,我有一个购物车,它可以装满不同种类的物品,在这个例子中是高尔夫球和高尔夫球杆,它们有自己的选择。
下面的代码出现以下错误:
TS2339: Property 'color' does not exist on type '{ color: "blue" | "red" | "white"; } | { variant: "wedge" | "putter"; }'.
Property 'color' does not exist on type '{ variant: "wedge" | "putter"; }'.
type ProductGolfBall = {
type: "golfball";
options: {
color: "blue" | "red" | "white";
};
};
type ProductGolfClub = {
type: "golfclub";
options: {
variant: "wedge" | "putter";
};
};
type CartItem = ProductGolfBall | ProductGolfClub;
type CartItems = Array<CartItem>;
const cart: CartItems = [
{
type: "golfball",
options: {
color: "blue"
}
},
{
type: "golfclub",
options: {
variant: "wedge"
}
},
{
type: "golfclub",
options: {
variant: "putter"
}
}
];
const golfball = cart.find((item) => item.type === "golfball");
if (golfball) { // Check that it's truthy
// According to typescript this can still be either ProductGolfClub or ProductGolfBall
console.log(golfball.type)
console.log(golfball.options.color) // Produces the TS2339 error above
}
现在我只是不明白为什么 golfball 变量仍然可以是 ProductGolfClub 当查找操作仅对 type 属性为 golfball 的数组项返回 true 时。
我可以将 golfball 变量设置为 ProductGolfBall,但必须有其他方法让 typescript 了解变量的类型。
【问题讨论】:
标签: typescript