3

Is there a way to extend Error in TypeScript >= 3.3 so it would correctly work with 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
}
Alex Craft
  • 13,598
  • 11
  • 69
  • 133

1 Answers1

1

Thanks to @moronator, you have to add magic line

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
}
Alex Craft
  • 13,598
  • 11
  • 69
  • 133