Skip to content

Instantly share code, notes, and snippets.

@VictorQueiroz
Created March 3, 2025 17:56
Show Gist options
  • Select an option

  • Save VictorQueiroz/d9b22b491b441b9613fb27121f511f3b to your computer and use it in GitHub Desktop.

Select an option

Save VictorQueiroz/d9b22b491b441b9613fb27121f511f3b to your computer and use it in GitHub Desktop.
TypeScript must-know

Questions

TypeScript and built-in error-checks

Stack Overflow

Solutions

Read https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work

Now, a complete implementation of @Mathyn and @TmTron answers:

/**
 * Base Error.
 */
class BaseError extends Error {
  constructor(message?: string) {
    const trueProto = new.target.prototype;
    super(message);
    Object.setPrototypeOf(this, trueProto);
  }
}

class Err1 extends BaseError {}
const e1 = new Err1();
console.log(e1 instanceof Err1); // true
console.log(e1 instanceof Error); // true

class Err2 extends Err1 {}
const e2 = new Err2();
console.log(e2 instanceof Err1); // true
console.log(e2 instanceof Err2); // true
console.log(e2 instanceof Error); // true

class NoBaseErr extends Error {}
const x = new NoBaseErr();
console.log(x instanceof Error); // true
console.log(x instanceof NoBaseErr); // false !!!
Package
import BaseError from 'ts-base-error';

See: https://www.npmjs.com/package/ts-base-error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment