3

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?

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.