TS 를 ES5 로 내리면 Error 를 상속한 클래스의 instanceof 가 깨진다 — super() 직후 프로토타입을 직접 맞춘다. ES2015 이상 타깃이면 필요 없다.1

class CustomError extends Error {
  name = 'CustomError'

  constructor(message?: string) {
    super(message)

    Object.setPrototypeOf(this, CustomError.prototype)
  }
}

try {
  throw new CustomError('This is a custom error message.')
} catch (error) {
  if (error instanceof CustomError) {
    console.log('CustomError occurred:', error.message)
    console.log('Error name:', error.name)
  } else {
    console.log('An error occurred:', error)
  }
}

Footnotes

  1. TypeScript Breaking Changes — TypeScript 2.1: “constructor functions for Error, Array, and the like use ECMAScript 6’s new.target to adjust the prototype chain; however, there is no way to ensure a value for new.target when invoking a constructor in ECMAScript 5.” / “As a recommendation, you can manually adjust the prototype immediately after any super(...) calls.” ↩

`#287`