从TypeType中的Error中断`instanceof`检查中继承 [英] Inherit from Error breaks `instanceof` check in TypeScript

查看:101
本文介绍了从TypeType中的Error中断`instanceof`检查中继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can someone explain me why the error instanceof CustomError part of below code is 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对象,有什么特别之处吗?我想制作自己的错误类型以供检查.

Is something special about Error object? I would like to make my own error types that i can check against.

顺便说一句,我已经在最新的 TypeScript游乐场

Btw i've checked the above code on latest TypeScript Playground

推荐答案

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.

拥有自己的错误对象并保留某些原始Error作为属性可能更好:

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

这篇关于从TypeType中的Error中断`instanceof`检查中继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆