Typescript - Extending Error class

前端 未结 6 967
一向
一向 2020-11-27 03:07

I\'m trying to throw a custom error with my \"CustomError\" class name printed in the console instead of \"Error\", with no success:

class CustomError extend         


        
6条回答
  •  误落风尘
    2020-11-27 03:38

    As of TypeScript 2.2 it can be done via new.target.prototype. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#example

    class CustomError extends Error {
        constructor(message?: string) {
            super(message); // 'Error' breaks prototype chain here
            this.name = 'CustomError';
            Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
        }
    }
    

提交回复
热议问题