示例:
Error构造函数(new Error([message[, fileName[, lineNumber]]])
)具有两个我要使用的可选参数(fileName和lineNumber),但是TypeScript编译器抱怨以下错误消息Expected 0-1 arguments, but got 3
。
防止TypeScript中此类错误的正确方法是什么?
答案 0 :(得分:1)
看着上面链接的Error
documentation,我看到了:
message
:可选。易于理解的错误描述。
fileName
:可选。创建的fileName
对象上Error
属性的值。默认为包含名为Error()
构造函数的代码的文件名。
lineNumber
:可选。创建的lineNumber
对象上Error
属性的值。默认为包含Error()
构造函数调用的行号。
那些黄色的大警告标题为“此API尚未标准化”。 (您可以在悬停时看到)。如果您查看文档底部的compatibility table,则当前表示只有Firefox支持这些参数。其他浏览器和节点则没有。
所以我想TypeScript不在standard library definition for the Error
constructor中包含它们的原因是因为不能保证它可以在所有JavaScript环境中正常工作。
现在,如果您确定,将在其中运行发出的JS代码的环境确实支持这些参数(即,如果仅在Firefox中运行代码),则可以在您自己的TypeScript代码中使用declaration merging来添加适当的签名:
// 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
根据需要。
希望有所帮助;祝你好运!