Typescript 打字与遗传
我可以像这样为函数Typescript 打字与遗传,typescript,Typescript,我可以像这样为函数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 } CustomEr
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”上不存在属性“message”。(2339)
我怎样才能解决这个问题
已更新由于
CustomErr
是无法更改的第三方库,请不要将代码混合在一起
//第三方-lib.js
函数CustomErr(消息:字符串){
var err=新错误(消息)
setPrototypeOf(err,CustomErr.prototype)
返回错误
}
CustomErr.prototype=Object.create(Error.prototype{
名称:{value:'自定义错误',可枚举:false}
})
//第三方-lib.d.ts
声明类CustomErr扩展错误{
构造函数(消息:string);
}
//my-code.ts
const err=new CustomErr(“出错”)//现在没有错误
console.log(错误消息)
这不起作用,因为我还需要坚持使用CustomErr
函数。这可能是一个TypeScript错误,但为什么必须坚持将其作为函数使用?它来自第三方库,我需要为其创建打字。请在单独的*.d.ts
中执行,并在单独的*.ts
中使用,不要与该函数混合使用。