打字和继承

时间:2020-08-03 17:09:16

标签: 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
}

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)

我该如何解决?

Playground

1 个答案:

答案 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)