[英]Conditional properties and switch statements in TypeScript
我定义了这些类型:
type ItemWithName = {
type: "ItemWithName";
name: string;
a: { name: string } ;
};
type ItemWithValue = {
type: string;
name: string;
b: { value: number } ;
};
export type Item = ItemWithName | ItemWithValue;
我有一个 function 从 object 中提取某个值:
const extractValue = (item: Item) => {
switch (item.type) {
case "ItemWithName":
return item.a.name; // TS2339: Property 'a' does not exist on type 'Item'.
case "ItemWithValue":
return item.b.value;
}
};
但我收到此错误: TS2339: Property 'a' does not exist on type 'Item'.
我不完全确定如何让 TypeScript 明白,如果 object 的类型是“ItemWithValue”,则有一个属性 a。
注意:这是对我的特定问题的一个小抽象,实际上我还有更多这些类型。
如果 object 的类型值为"ItemWithName"
,则预期的行为是 TypeScript 检测到项目的类型为ItemWithName
不幸的是,这目前不适用于 Typescript。
type-fest有一个包装类型LiteralUnion
用于问题中引用的问题。 但是,您不能像type Item = LiteralUnion<ItemWithName, ItemWithValue>
那样使用它。
所以这是我目前的两种可能性:
const extractValue = (item: Item) => {
switch (item.type) {
case "ItemWithName":
const itemWithName = item as ItemWithName;
return itemWithName.a.name;
case "ItemWithValue":
return item.b.value;
}
};
注意:这是对我的特定问题的一个小抽象,实际上我还有更多这些类型。
而不是使用
type ItemWithValue = {
type: string;
name: string;
b: { value: number } ;
};
您可以创建一个联合所有可能类型的类型,例如
type ItemWithValue = {
type: 'ItemWithValue' | 'OtherItemWithValue' | 'AgainAnItemWithValue';
name: string;
b: { value: number } ;
};
使用type: Exclude<string, 'ItemWithName'>
真的很酷。 但这也行不通,正如您在这个讨论的问题中看到的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.