簡體   English   中英

TypeScript 中的條件屬性和 switch 語句

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

這是 GitHub 關於類似問題的問題。

type-fest有一個包裝類型LiteralUnion用於問題中引用的問題。 但是,您不能像type Item = LiteralUnion<ItemWithName, ItemWithValue>那樣使用它。

所以這是我目前的兩種可能性:

  1. 可能性:簡單地轉換類型
const extractValue = (item: Item) => {
  switch (item.type) {
    case "ItemWithName":
      const itemWithName = item as ItemWithName;
      return itemWithName.a.name;
    case "ItemWithValue":
      return item.b.value; 
  }
};
  1. 可能性:列出所有可能的類型

注意:這是對我的特定問題的一個小抽象,實際上我還有更多這些類型。

而不是使用

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM