n1stre
n1stre

Reputation: 6086

Typescript: types for custom Error class as an argument

I have a custom Error404 class and a function run to which I want to pass this error constructor:

class Error404 extends Error {
  constructor(message: string) {
    super(message);
    this.name = "404";
    this.message = message;
  }
}

function run(MyErr: ErrorConstructor) {
  throw new MyErr("test");
}

But when trying to invoke it I get:

run(Error404)
    ^^^^^^^^
    class Error404
    Argument of type 'typeof Error404' is not assignable to parameter of type 'ErrorConstructor'. 
    Type 'typeof Error404' provides no match for the signature '(message?: string): Error'.ts(2345)

What am I doing wrong? How to fix it?

Upvotes: 3

Views: 7639

Answers (1)

Lesiak
Lesiak

Reputation: 25966

Note that ErrorConstructor does provide not only the possibility to construct via new, but also via callable:

interface ErrorConstructor {
    new(message?: string): Error;
    (message?: string): Error;
    readonly prototype: Error;
}

declare var Error: ErrorConstructor;

Thus, new Error instances can be created via:

  • new Error('message')
  • Error('message')

Clearly your Error404 does not meet the second requirement - it can be only constructed via new.

I would try to keep things simple, and modify the signature of run:

class Error404 extends Error {
  constructor(message: string) {
    super(message);
    this.name = "404";
  }
}

function run(MyErr: new(message: string) => Error): never {
  throw new MyErr('test');
}

run(Error404);

Upvotes: 4

Related Questions