簡體   English   中英

打字稿 - 基於 for 列表中的值的條件類型

[英]Typescript - conditional types based on value in a for of list

所以這些是我的類型:

export type typeOne = {
  A: string;
  B: string;
};

export type typeTwo = {
  A: string;
  C: string;
};

export type Result = typeOne | typeTwo; //condition 

這是用例:

for (const item: Result of list) {
   const something = item.B ? 'B exsist' : item.C;
   return something;
}

它不斷返回錯誤:

TS2339:“結果”類型上不存在屬性“B”。 類型“typeTwo”上不存在屬性“B”。

還有另一個:

TS2339:“結果”類型上不存在屬性“C”。 類型“typeOne”上不存在屬性“C”。

你知道我該如何解決這個問題嗎?

注意:循環也會發生以下錯誤:

TS2483:“for...of”語句的左側不能使用類型注釋。

您可以使用in類型保護來區分具有不相等鍵的對象類型的聯合:

for (const item: Result of list) {
   const something = "B" in item ? 'B exsist' : item.C;
   return something;
}

游樂場鏈接

TypeScript 的一個細微差別是,如果你有一個聯合類型的對象,你只能訪問它們之間的公共字段。 使用這種技術來添加一個可以區分兩者的公共字段是很常見的。 例如:

export type typeOne = {
  type: 'one';
  A: string;
  B: string;
};

export type typeTwo = {
  type: 'two'
  A: string;
  C: string;
};

export type Result = typeOne | typeTwo; //condition 

for (const item: Result of list) {
   const something = item.type === 'one' ? 'B exists' : item.C;
   return something;
}

在這種情況下, type充當鑒別器。 在此處閱讀更多信息: https : //basarat.gitbook.io/typescript/type-system/discriminated-unions


或者,您可以創建自定義類型保護來區分這兩種類型。 這涉及一個函數,該函數接受您的聯合類型並在運行時評估該值是否為特定類型。 您可以使用類型斷言訪問聯合中的非共享字段:

function isTypeOne(result: Result): result is typeOne {
  return (result as typeOne).B !== undefined;
}

for (const item: Result of list) {
   const something = isTypeOne(item) ? 'B exists' : item.C;
   return something;
}

在這里,如果isTypeOne失敗, typeOne可以安全地從Result消除,因此類型被推斷為typeTwo

關於您提到的最后一個錯誤:

“TS2483:'for...of' 語句的左側不能使用類型注釋。”

Result類型定義應該是list聲明的一部分。 這樣,就無需指定語句的左側是Result

例如,假設list是一個數組:

const list: Array<Result> = [{A: 'foo', B: 'bar'}, {A: 'foo', C: 'baz'}]
for (const item of list) {
  // Run code from other answers here
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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