我有一个有两个值的对象。我想根据对等方的值有条件地键入check one值。我已经研究了各种解决方案,但我无法让它按我希望的方式工作。
我可以做这样的事情(来源(:
type TypeFruit = "apples" | "bananas";
type TypeMetal = "iron" | "copper";
type InterfaceItem =
| {
item: "fruit";
type: TypeFruit;
}
| {
event: "metal";
type: TypeMetal;
};
type ItemTypeParameters = InterfaceItem["type"];
type Item = {
item: "fruit" | "metal";
type: ItemTypeParameters;
};
但这产生了:
// ✅ Correct
assignItem({
item: "fruit",
type: "apples",
});
// ✅ Correct
assignItem({
item: "fruit",
type: "copper",
});
我想做的是设置代码,这样结果会是这样的:
// ✅ Correct
assignItem({
item: "fruit",
type: "apples",
});
// ❌ Wrong
assignItem({
item: "fruit",
type: "copper",
});
有办法做到这一点吗?我看过ConditionalTypes,这似乎是我想要的,但发现它们令人困惑,而且似乎适用于其他场景,如有条件地扩展类型。
您的原始InterfaceItem
已经为您提供了所需的形状-其中item: "fruit"
必须与TypeFruit
配对(并且仅与之配对(。你所需要的就是这些,而不是别的。
type TypeFruit = "apples" | "bananas";
type TypeMetal = "iron" | "copper";
type InterfaceItem =
| {
item: "fruit";
type: TypeFruit;
}
| {
event: "metal";
type: TypeMetal;
};
declare const assignItem: (item: InterfaceItem) => null;
assignItem({ // Works
item: "fruit",
type: "apples",
});
assignItem({ // Fails
item: "fruit",
type: "copper",
});