Typescript - Extending Error class

前端 未结 6 956
一向
一向 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:45

    It works correctly in ES2015 (https://jsfiddle.net/x40n2gyr/). Most likely, the problem is that the TypeScript compiler is transpiling to ES5, and Error cannot be correctly subclassed using only ES5 features; it can only be correctly subclassed using ES2015 and above features (class or, more obscurely, Reflect.construct). This is because when you call Error as a function (rather than via new or, in ES2015, super or Reflect.construct), it ignores this and creates a new Error.

    You'll probably have to live with the imperfect output until you can target ES2015 or higher...

提交回复
热议问题