打字稿:自定义错误类的类型作为参数

时间:2020-04-30 11:36:15

标签: javascript typescript

我有一个自定义Error404类和一个函数run,我想将此错误构造函数传递给该函数:

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

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

但是当尝试调用它时,我得到了:

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)

我在做什么错?如何解决?

1 个答案:

答案 0 :(得分:2)

请注意,ErrorConstructor不仅提供了通过new进行构造的可能性,而且还提供了通过可调用进行构造的可能性:

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

declare var Error: ErrorConstructor;

因此,可以通过以下方式创建新的错误实例:

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

很显然,您的Error404不满足第二个要求-只能通过new构造。

我将尝试使事情保持简单,并修改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);
相关问题