![](/img/trans.png)
[英]When calling a JavaScript function from TypeScript, how do I override the inferred type?
[英]How do I override type of a standard library function in TypeScript?
我正在開發一個 polyfill,它通過向 reviver 回調 function 添加可選的第三個參數來擴展JSON.parse()
function 的行為。
polyfill 應該像這樣為最終用戶導入:
import 'my-polyfill';
JSON.parse()
在node_modules/typescript/lib/lib.es5.d.ts
中定義如下:
// lib.es5.d.ts
interface JSON {
// …
parse(
text: string,
reviver?: (this: any, key: string, value: any) => any
): any;
// …
}
如何覆蓋此定義,以便在安裝/導入 polyfill 時使用我的定義? 例如:
interface ContextType {
// …
}
interface JSON {
parse<Type = any>(
text: string,
reviver?: (
key: string,
value: any,
context?: ContextType
) => any
): Type;
}
您可以創建聲明文件並將其命名為polyfill.d.ts
等。 然后,您應該使用標准方式擴展全局類型,如下所示:
declare global {
interface JSON {
// Here, you should write your own implementation of `parse` function.
parse(variable: string): void;
}
}
export {};
export
是 TypeScript 所必需的,您可以在此答案及其評論中了解更多信息。
不要忘記,當您創建一個單獨的庫時,該文件應該存在於最終構建目錄中。 因此,當某些用戶安裝您的 package 並導入它時,文件polyfill.d.ts
將由 TypeScript 自動應用。
我不確定您是否能夠制作具有自己功能的 TypeScript 傳輸聲明文件 ( .d.ts
)。 為此,我們應該使用此處描述的一些 hack。 我們應該將文件命名為polyfill.ts
而不是polyfill.d.ts
並將其導入到庫的index.ts
文件中,這樣它將被 TypeScript 導入並傳輸到構建目錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.