javascript - Typescript: types for custom Error class as an argument - Stack Overflow

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

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?

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?

Share Improve this question asked Apr 30, 2020 at 11:36 n1stren1stre 6,0964 gold badges23 silver badges42 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745116077a4612134.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信