在Typescript中用cause创建抽象类时出现的问题



最初,我想在实现后创建一个带有cause字段的抽象错误类。

abstract class CustomError extends Error {
constructor(message: string, options: { cause: any }) {
super(message, options);
Object.setPrototypeOf(this, new.target.prototype);
}
}
class NewError extends CustomError {
constructor(message: string) {
super(message, { cause: "helloworld "});
}
}
const a = new NewError("helloworld");
console.log("a", a, "a.cause", a.cause)

然而,我得到了错误

(parameter) options: {
cause: any;
}
Expected 0-1 arguments, but got 2.(2554)

目前这是我的解决方案,但我希望我的第一个实现工作,直接使用Error对象的cause字段。

谁能给我解释一下为什么第一个版本不行?可能的解决方案是什么?谢谢你。
abstract class CustomError extends Error {
cause: string | undefined = undefined;
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
}
}
class NewError extends CustomError {
constructor(message: string) {
super(message);
this.cause = "helloworld";
}
}
const a = new NewError("helloworld");
console.log("a", a, "a.cause", a.cause)

如果我删除抽象类,它也工作。然而,我的目标是能够保持抽象类并使其工作。

在ES2022中引入了Error实例的cause属性。如果你想在你的TypeScript代码中使用它,你应该将你的--target编译器设置至少增加到"ES2022"(或者至少改变你的--lib编译器设置来包含它)。如果你这样做,事情就会开始工作。

请记住,如果你试图支持旧的运行时,那么你可能想要填充Error(如core-js中的这个填充)或使用您的解决方案。

Playground链接到--target"ES2022"的代码。

最新更新