Inherit from Error breaks `instanceof` check in TypeScript

*爱你&永不变心* 提交于 2019-12-01 22:29:00

Turns out an change has been introduced in TypeScript@2.1 that breaks this pattern. The whole breaking change is described here.

In general it seems it's too complicated/error to even go with this direction.

Probably better to have own error object and keeps some original Error as an property:

class CustomError {
    originalError: Error;

    constructor(originalError?: Error) {
        if (originalError) {
            this.originalError = originalError
        }
    }
}

class SpecificError extends CustomError {}

const error = new SpecificError(new Error('test'));

console.log(error instanceof CustomError); // true
console.log(error instanceof SpecificError); // true
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!