簡體   English   中英

使用TypeScript時如何處理瀏覽器API中的可選參數

[英]How to deal with optional parameters in browser API when using TypeScript

例子:

Error構造函數( new Error([message[, fileName[, lineNumber]]]) )有兩個我想使用的可選參數(fileName 和 lineNumber),但 TypeScript 編譯器抱怨以下錯誤消息Expected 0-1 arguments, but got 3

在 TypeScript 中防止這種錯誤的正確方法是什么?

Error您上面鏈接的Error文檔,我看到了:

  • message :可選。 人類可讀的錯誤描述。

  • fileName This API has not been standardized. : 可選的。 創建的Error對象上的fileName屬性的值。 默認為包含調用Error()構造函數的代碼的文件的名稱。

  • lineNumber This API has not been standardized. : 可選的。 創建的Error對象上的lineNumber屬性的值。 默認為包含Error()構造函數調用的行號。

那些大黃色警告的標題是“此 API 尚未標准化”。 (您可以在懸停時看到)。 如果您查看文檔底部的兼容性表,它目前表示只有 Firefox 支持這些參數。 其他瀏覽器和節點沒有。

所以我猜 TypeScript 沒有將它們包含在Error構造函數的標准庫定義中的原因是因為它不能保證在所有 JavaScript 環境中都能工作。


現在,如果您確定運行發出的 JS 代碼的環境確實支持這些參數(即,如果您只打算在 Firefox 中運行代碼),則可以在自己的 TypeScript 代碼中使用聲明合並來添加適當的簽名:

// assuming your code is in a module, so using global augmentation here
declare global {
  interface ErrorConstructor {
    new(message?: string, fileName?: string, lineNumber?: number): Error;
  }
}

然后編譯器不會警告你:

export const iAmInAModule = true;
throw new Error("Badness happened", "badthing.js", 123); // no compiler warning now

如你所願。


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

暫無
暫無

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

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