gpt4 book ai didi

typescript - TS2339 : Array. 在有区别的联合中找到没有正确推断类型

转载 作者:行者123 更新时间:2023-12-04 10:21:21 27 4
gpt4 key购买 nike

在这个例子中,我有一个购物车,可以装满不同种类的物品,在这种情况下是高尔夫球和高尔夫球杆,它们有自己的选择。

Typescript Playground link

我收到以下代码的以下错误:

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当 find 操作仅对 type 的数组项返回 true 时属性是 golfball .

我可以设置 golfball变量为 ProductGolfBall ,但必须有其他方式让 typescript 了解变量的类型。

最佳答案

不幸的是,TS 无法从这种情况下开箱即用地制作类型保护。
但是您可以通过明确说明该功能将确保什么来手动进行,请考虑:

function isGolfBall(item: CartItem): item is ProductGolfBall {
return item.type === "golfball";
}

const golfball = cart.find(isGolfBall)

if (golfball) { // Check that it's truthy
console.log(golfball.type)
console.log(golfball.options.color) // no error 👌
}

最重要的是 :item is ProductGolfBall这意味着我们明确地说这个函数将是一个类型保护,它只为 ProductGolfBall 传递(返回真)。 .

内联解决方案还可以:
const golfball = cart.find((item): item is ProductGolfBall => item.type === "golfball")

关于typescript - TS2339 : Array. 在有区别的联合中找到没有正确推断类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60828674/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com