如何在TypeScript中扩展Error类

时间:2019-03-11 19:23:11

标签: typescript

有没有一种方法可以在TypeScript> = 3.3中扩展Error,使其可以与instanceof一起正常工作?

class MyError extends Error {
  constructor(
                    message: string,
    public readonly details: string
  ) { super(message) }
}

try {
  throw new MyError('some message', 'some details')
} catch (e) {
  console.log(e.message)            // Ok
  console.log(e.details)            // Ok
  console.log(e instanceof MyError) // Wrong, prints false
}

1 个答案:

答案 0 :(得分:1)

感谢@moronator,您必须添加魔术线

class MyError extends Error {
  constructor(
                    message: string,
    public readonly details: string
  ) { 
    super(message) 

    // This line
    Object.setPrototypeOf(this, MyError.prototype)
  }
}

try {
  throw new MyError('some message', 'some details')
} catch (e) {
  console.log(e.message)            // Ok
  console.log(e.details)            // Ok
  console.log(e instanceof MyError) // Works
}