从 Error 继承会破坏 TypeScript 中的“instanceof”检查

Inherit from Error breaks `instanceof` check in TypeScript

有人能解释一下为什么下面代码的 error instanceof CustomError 部分是 false 吗?

class CustomError extends Error {}

const error = new CustomError();

console.log(error instanceof Error); // true
console.log(error instanceof CustomError); // false ???

class ParentClass {}
class ChildClass extends ParentClass { }

const child = new ChildClass();

console.log(child instanceof ParentClass); // true
console.log(child instanceof ChildClass); // true

Error 对象有什么特别之处吗?我想制作我自己的错误类型,我可以检查。

顺便说一下,我已经在最新的 TypeScript Playground

上检查了上面的代码

原来 TypeScript@2.1 that breaks this pattern. The whole breaking change is described here 中引入了一个变化。

总的来说似乎 complicated/error 甚至不适合这个方向。

拥有自己的错误对象并保留一些原始 Error 作为 属性:

可能更好
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