簡體   English   中英

如何將變量轉換為特定類型以說服打字稿無處不在?

[英]How to cast a variable to a particular type to convince typescript that everwhere?

出於 IE 的原因,我需要構建一個自定義錯誤,但是,盡我所能,必須使用構造函數檢查錯誤。

customError instanceof CustomError; // false
customError.constructor === CustomError; // true

現在我怎樣才能在 if 語句中說服打字稿呢?

if (customError.constructor === CustomError) {
  customError.customMethod1() // typescript complaints
  customError.customMethod2() // typescript complaints
  customError.customMethod3() // typescript complaints
  customError.customMethod4() // typescript complaints
}

編輯:

背景是當你編譯到 ES5 時,一些繼承是不兼容的。

有沒有一種方法可以讓我投了一次,沒有使用as ,每次我使用變量?

到目前為止,使用它的唯一方法是:

const myCustomError = (customError as CustomError)

對其他聰明的想法持開放態度。

編寫用戶定義的類型保護

function isCustomError(x: any): x is CustomError {
    return x.constructor === CustomError;
}

並使用它:

if (isCustomError(err)) {
    err.customMethod1();
}

看到這個游樂場

暫無
暫無

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

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