Here is a code snippet optimized for displaying custom errors in Chrome Devtools, Node.js, and other platforms. The inspiration for this came from this specific answer on StackOverflow.
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 }
})
However, when attempting to convert the code 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 }
})
Using
throw new CustomErr("something went wrong")
results in the following error message:
'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.ts(7009)
I am seeking guidance on how to properly annotate my code with types. Additionally, if you have an alternative solution that achieves the same behavior in Chrome DevTools, please share it. Thank you!
EDIT: It is important to note that I need to support older browsers, therefore ES6 classes cannot be used. Converting classes to ES6 is also not preferred due to the impact on the size of my lightweight library.
To summarize, how can I correctly add type annotations to the current code?