<T扩展错误>无法解析为打字稿

时间:2019-07-21 17:21:59

标签: typescript

我的接口定义为:

export interface IErrorIdentification {
  errorClass?: new <T extends Error>() => T;
  code?: string;
  name?: string;
  messageContains?: string;
}

但是errorClass属性让我很合适。使用此代码时:

context.errorMeta.add(
  404,
  { errorClass: HandledError },
  { callback: e => cbResult }
);

第二个参数{ errorClass: HandledError }键入 IErrorIdentificaiton 时,出现以下错误:

error

通过以下检查,它可以在运行时按预期运行:

e instanceof i.identifiedBy.errorClass

错误(e)也作为{em> Error实例测试为阳性,考虑到HandledError被定义为:

export class HandledError extends Error { ... }

鉴于所有这些,我不确定为什么我会遇到任何错误,并且错误文本没有帮助我。谁能指出我做错了什么?

1 个答案:

答案 0 :(得分:3)

errorClass?: new <T extends Error>() => T;

这并不意味着您认为的意思。这意味着“ errorClass应该是通用的东西,我可以在其上调用new并选择任何错误类型。”也就是说,对于所有扩展T的{​​{1}},Errornew应该能够返回THandledError不满足要求,因为它不能返回TypeError或任何其他类型的错误。老实说,我不确定Typescript是否可以构造一个满足该约束的(非any)值。

您想要的内容是“存在T返回new的{​​{1}}”。这就是所谓的存在性类型,Typescript不支持。因此,您有两种选择。如果您不关心特定类型的错误,只需放下外观并让T返回new

Error

另一方面,如果出于某些原因确实需要export interface IErrorIdentification { errorClass?: new() => Error; } 值,请对接口进行参数设置。

T