簡體   English   中英

打字稿strictNullChecks錯誤,當不可能

[英]Typescript strictNullChecks error when not possible

我正在嘗試為我的項目打開strictNullChecks設置,但是以下代碼片段中有一個非常奇怪的錯誤:

toasters.forEach((toster: ToasterObject) => {
  if (toaster.brandName) {
    //This line works just fine
    let y = toaster.brandName.toLowerCase() === 'test brand name';

    //This line has the error
    if (!itemsArray.some(item => item.brandName.toLowerCase() === toaster.brandName.toLowerCase())) {
        //do stuff
    }
  }
});

錯誤消息的if語句中帶有下划線的錯誤消息帶有toaster.brandName ,並帶有以下錯誤文本: error TS2532: Object is possibly 'undefined'. 如果可以在上面的y =行上使用該對象,為什么在if語句中使用該對象會引起問題? 我該如何解決這個問題,這樣才能避免出現此錯誤?

控制流分析很難 這里的問題是編譯器不知道是否,何時或如何調用回調。 因此,從(大概是) string | undefined縮小了toaster.brandName范圍string | undefined string | undefinedstringarray.some()回調內部不再有效。 如果要幫助編譯器,則應將toaster.brandName的已知定義值分配給const ,編譯器希望該值始終保持相同的窄類型:

toasters.forEach((toster: ToasterObject) => {
  if (toaster.brandName) {
    const toasterBrandName = toaster.brandName; // string, now and forever

    if (!itemsArray.some(item => item.brandName.toLowerCase() === toasterBrandName.toLowerCase())) {
        //do stuff
    }
  }
});

希望能有所幫助; 祝好運!

暫無
暫無

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

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