问题描述
以下是最适合在Chrome Devtools,Node.js等中显示自定义错误的代码。基于。
The following is the code that works best for displaying custom errors in Chrome Devtools, Node.js, etc. Based on this StackOverflow answer.
function CustomErr (message) {
var err = new Error(message)
Object.setPrototypeOf(err, CustomErr.prototype)
return err
}
CustomErr.prototype = Object.create(Error.prototype, {
name: { value: 'Custom Error', enumerable: false }
})
但是,当我将其转换为Typescript时:
However, when I convert it to Typescript:
function CustomErr (message: string) {
var err = new Error(message)
Object.setPrototypeOf(err, CustomErr.prototype)
return err
}
CustomErr.prototype = Object.create(Error.prototype, {
name: { value: 'Custom Error', enumerable: false }
})
呼叫抛出新的CustomE rr(出问题了)
显示此错误:
'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.ts(7009)
我该怎么办正确键入代码注释?如果您可以找到其他等效的代码解决方案,请随时提出建议,但是它在Chrome DevTools中必须具有相同的行为(仅我尝试过的所有解决方案都很好地显示了一个自定义错误名称)。谢谢!
What can I do to correctly type-annotate my code? If you can find another equivalent code solution, feel free to suggest it, but it MUST have the same behavior in Chrome DevTools (this alone of all solutions I tried displays a custom error name nicely). Thanks!
编辑:
需要支持较旧的浏览器,所以我不能使用ES6类。我不希望将类转换为ES6,因为我正在创建一个轻量级的库,而一个类polyfill仅占我整个代码大小的10%。
EDIT:Need to support older browsers, so I can't use ES6 classes. I'd prefer not to transpile classes to ES6 because I'm creating a lightweight library, and a class polyfill alone is 10% of my entire codesize.
,如何注释现在的代码?
So to recap, how can I annotate the code I have now?
推荐答案
您可以声明类,但可以使用函数来实现。这样输出(生成的javascript)将不会受到影响,但是打字稿会将 CustomErr
视为可更新:
You can declare class, but implement it with a function. This way output (the resulting javascript) won't be affected, but typescript will treat the CustomErr
as a "newable":
declare class CustomErr extends Error {
constructor(message: string);
}
function CustomErr(message: string) {
var err = new Error(message)
Object.setPrototypeOf(err, CustomErr.prototype)
return err
}
CustomErr.prototype = Object.create(Error.prototype, {
name: { value: 'Custom Error', enumerable: false }
})
throw new CustomErr("something went wrong") // no error now
这篇关于Typescript:目标为缺少构造签名的“ new”表达式隐式为“ any”类型。ts(7009)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!