最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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);
发布评论

评论列表(0)

  1. 暂无评论