如何在TypeScript中扩展Error类

问题描述 投票:3回答:1

有没有办法在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
}
typescript
1个回答
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
}
© www.soinside.com 2019 - 2024. All rights reserved.