Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit from Error breaks `instanceof` check in TypeScript

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

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

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

like image 463
Adam Szmyd Avatar asked May 11 '17 09:05

Adam Szmyd


1 Answers

Turns out an change has been introduced in [email protected] 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
like image 126
Adam Szmyd Avatar answered Sep 28 '22 00:09

Adam Szmyd