[英]How do I override type of a standard library function in TypeScript?
I'm working on a polyfill that extends the behavior of the JSON.parse()
function by adding an optional third argument to the reviver callback function.我正在开发一个 polyfill,它通过向 reviver 回调 function 添加可选的第三个参数来扩展
JSON.parse()
function 的行为。
The polyfill should be imported like this for the end users: polyfill 应该像这样为最终用户导入:
import 'my-polyfill';
The JSON.parse()
is defined in the node_modules/typescript/lib/lib.es5.d.ts
like this: 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;
// …
}
How do I override this definition, so when the polyfill is installed/imported my definition is used instead?如何覆盖此定义,以便在安装/导入 polyfill 时使用我的定义? Eg:
例如:
interface ContextType {
// …
}
interface JSON {
parse<Type = any>(
text: string,
reviver?: (
key: string,
value: any,
context?: ContextType
) => any
): Type;
}
You could create declarations file and name it, for example, as polyfill.d.ts
.您可以创建声明文件并将其命名为
polyfill.d.ts
等。 Then, you should use standard way of extending global types as follows:然后,您应该使用标准方式扩展全局类型,如下所示:
declare global {
interface JSON {
// Here, you should write your own implementation of `parse` function.
parse(variable: string): void;
}
}
export {};
export
is required by TypeScript and you can learn more about it in this answer and its comments. export
是 TypeScript 所必需的,您可以在此答案及其评论中了解更多信息。
Don't forget, that when you create a separate library, this file should exist in final build directory.不要忘记,当您创建一个单独的库时,该文件应该存在于最终构建目录中。 So, when some user installs your package and imports it, file
polyfill.d.ts
would be automatically applied by TypeScript.因此,当某些用户安装您的 package 并导入它时,文件
polyfill.d.ts
将由 TypeScript 自动应用。
I am not sure, that you are able to make TypeScript transfer declarations file ( .d.ts
) with its own functionality.我不确定您是否能够制作具有自己功能的 TypeScript 传输声明文件 (
.d.ts
)。 To do this, we should use some hack, described here .为此,我们应该使用此处描述的一些 hack。 We should name file not
polyfill.d.ts
, but polyfill.ts
and import it in library's index.ts
file, so it would be imported by TypeScript and transferred to build directory.我们应该将文件命名为
polyfill.ts
而不是polyfill.d.ts
并将其导入到库的index.ts
文件中,这样它将被 TypeScript 导入并传输到构建目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.