Inherit from Error breaks `instanceof` check in TypeScript

后端 未结 1 334
说谎
说谎 2021-01-13 08:38

Can someone explain me why the error instanceof CustomError part of below code is false ?

class CustomError extends Error {}

cons         


        
相关标签:
1条回答
  • 2021-01-13 08:46

    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
    
    0 讨论(0)
提交回复
热议问题