[英]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.