簡體   English   中英

TypeScript - 類型未定義不能分配給類型 ICustomType

[英]TypeScript - Type undefined is not assignable to type ICustomType

我對 TypeScript 很陌生,並試圖了解在我的代碼中處理這種情況的最佳方法是什么。

我的系統中有一組具有自定義類型的對象,我使用Array.find方法來獲取其中一個。 但是我收到一個編譯錯誤,說Type 'undefined' is not assignable to type IConfig

這是代碼示例 -

const config: IConfig = CONFIGS.find(({ code }) => code === 'default');
// Type 'undefined' is not assignable to type IConfig

我試圖將undefined添加為可能的類型,但隨后在使用此對象的下一行出現錯誤Object is possibly 'undefined' possible Object is possibly 'undefined' ,例如 -

const config: IConfig | undefined = CONFIGS.find(({ code }) => code === 'default');

// Object is possibly 'undefined'
if (config.foo) {
   return 'bar';
}

解決此類問題的最佳方法是什么?

如果數組中沒有任何內容通過回調測試, .find將返回undefined 如果您確定數組中存在default代碼,則使用非空斷言運算符:

const config: IConfig = CONFIGS.find(({ code }) => code === 'default')!;
//                                                                    ^

(如果您不確定它是否存在於數組中,您看到的警告是為了提示您在嘗試訪問它的屬性之前顯式測試該項目是否存在,否則有時您會收到運行時錯誤:

const config: IConfig = CONFIGS.find(({ code }) => code === 'default');

if (!config) {
  return 'No match found';
}
if (config.foo) {
   return 'bar';
}

)

暫無
暫無

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

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