【问题标题】:Inherit from Error breaks `instanceof` check in TypeScript从错误继承中断 TypeScript 中的“instanceof”检查
【发布时间】:2017-10-10 06:16:50
【问题描述】:

有人能解释一下为什么下面代码的 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 inheritance types instanceof


    【解决方案1】:

    原来TypeScript@2.1 中引入了一个改变,打破了这种模式。整个重大更改描述为here

    一般来说,这个方向似乎太复杂/错误。

    最好有自己的错误对象并保留一些原始的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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-18
      • 1970-01-01
      • 2021-03-09
      • 2022-06-11
      • 1970-01-01
      相关资源
      最近更新 更多