简体   繁体   English

使用TypeScript时如何处理浏览器API中的可选参数

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

Example:例子:

The Error constructor ( new Error([message[, fileName[, lineNumber]]]) ) has two optional parameters (fileName and lineNumber) that I would like to use but the TypeScript compiler complains with the following error message Expected 0-1 arguments, but got 3 . Error构造函数( new Error([message[, fileName[, lineNumber]]]) )有两个我想使用的可选参数(fileName 和 lineNumber),但 TypeScript 编译器抱怨以下错误消息Expected 0-1 arguments, but got 3

What is the proper way to prevent this kind of error in TypeScript?在 TypeScript 中防止这种错误的正确方法是什么?

Looking at the Error documentation you linked above, I see this: Error您上面链接的Error文档,我看到了:

  • message : Optional. message :可选。 A human-readable description of the error.人类可读的错误描述。

  • fileName This API has not been standardized. : Optional. : 可选的。 The value for the fileName property on the created Error object.创建的Error对象上的fileName属性的值。 Defaults to the name of the file containing the code that called the Error() constructor.默认为包含调用Error()构造函数的代码的文件的名称。

  • lineNumber This API has not been standardized. : Optional. : 可选的。 The value for the lineNumber property on the created Error object.创建的Error对象上的lineNumber属性的值。 Defaults to the line number containing the Error() constructor invocation.默认为包含Error()构造函数调用的行号。

Those big yellow warnings have the title "This API has not been standardized."那些大黄色警告的标题是“此 API 尚未标准化”。 (which you can see on hover). (您可以在悬停时看到)。 If you look at the compatibility table at the bottom of the documentation, it currently says that only Firefox supports those parameters.如果您查看文档底部的兼容性表,它目前表示只有 Firefox 支持这些参数。 Other browsers and node don't.其他浏览器和节点没有。

So I guess the reason TypeScript doesn't include them in its standard library definition for the Error constructor is because it's not guaranteed to work in all JavaScript environments.所以我猜 TypeScript 没有将它们包含在Error构造函数的标准库定义中的原因是因为它不能保证在所有 JavaScript 环境中都能工作。


Now if you're certain that the environment in which you will run your emitted JS code does support those parameters (ie, if you are only going to run the code in Firefox), you can use declaration merging in your own TypeScript code to add the appropriate signature:现在,如果您确定运行发出的 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;
  }
}

And then the compiler will not warn you:然后编译器不会警告你:

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

as you wanted.如你所愿。


Hope that helps;希望有所帮助; good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM