CodePark/ questions / Inheritance, overriding & Liskov
START PRACTICINGPRACTICE
Backend question · Object-oriented programming › Inheritance, overriding & Liskov

An older project compiles TypeScript with target: "ES5". What does this print?

class NotFoundError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "NotFoundError";
  }
}
const e = new NotFoundError("user 7");
console.log(e instanceof NotFoundError, e instanceof Error);
false true

It prints false true. ES5 has no real class, so TypeScript turns super(message) into Error.call(this, message). Error returns a new object and ignores your prototype, so the instance is a plain Error. Your catch block checking instanceof NotFoundError never matches.

"
true true" is the result with target ES2015 or later, where native classes extend Error correctly. With ES5 the fix is Object.setPrototypeOf(this, new.target.prototype) in the constructor. Newer TypeScript versions deprecate the ES5 target.