我可以像这样为函数CustomErr
创建类型:
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
在我要访问CustomErr.message
上存在的Error
之前,此方法工作正常:
类型“ CustomErr”上不存在属性“消息”。(2339)
我该如何解决?
答案 0 :(得分:1)
已更新,因为CustomErr
是无法更改的第三方库,因此请勿将代码混在一起。
// third-party-lib.js
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 }
})
// third-party-lib.d.ts
declare class CustomErr extends Error {
constructor(message: string);
}
// my-code.ts
const err = new CustomErr("something went wrong") // no error now
console.log(err.message)