typescript - 类型 ErrorConstructor 的 TypeScript 问题
问题描述
我正在尝试创建一个函数,该函数采用 ErrorConstructor 和消息,并通过一点转换的消息引发此错误。但是在尝试传递扩展基本错误的自定义错误构造函数时出现意外错误:
err<E extends ErrorConstructor>(Err: E, message: any): never {
throw new Err(`'${message}': at line ${this.line}, at column ${this.column}`)
}
class LexerError extends Error {name="LexerError"}
err(LexerError, 'Invalid token: ${some_token}') //here is the error
错误:Argument of type 'typeof LexerError' is not assignable to parameter of type 'ErrorConstructor'. Type 'typeof LexerError' provides no match for the signature '(message?: string | undefined): Error'
解决方案
命名的类型在 TypeScript 标准库ErrorConstructor
中定义为
interface ErrorConstructor {
new(message?: string): Error; // construct signature
(message?: string): Error; // call signature
readonly prototype: Error;
}
因此,为了使某物成为一个ErrorConstructor
,它不仅需要是具有构造签名的实际构造函数,还需要是具有返回实例的调用签名的普通函数。Error
你LexerError
只是一个构造函数,而不是一个普通的函数。
由于您只关心构造签名,因此您应该忘记ErrorConstructor
类型并直接使用构造签名:
function err<E extends new (message?: string) => Error>(Err: E, message: any): never {
throw new Err(
`'${message}': minimal reproducible examples don't have unrelated errors`
);
}
您可以验证现在一切都按预期工作:
class LexerError extends Error { name = "LexerError" }
err(LexerError, 'Invalid token: ${some_token}') // okay`
推荐阅读
- javascript - HTML & Javascript - 使用循环创建按钮不会“个性化” .onclick = {}
- php - 如何从另一个模型返回集合?
- c++ - 我正在尝试将我的 c++ 数组从第二个索引切到最后一个索引
- typescript - 如何从 firebase 获取动态属性的值
- android - Android recycler view位置出现index错误
- mongodb - 从 ansible 创建 mongodb 用户时出现 SCRAM-SHA-256 错误
- silverstripe - 如何使用 Silverstripe Fluent 通过 ::get() 访问区域设置字段值
- ios - 如何保存不同设备的游戏进度?
- angular - 基于复选框和表单验证无效的提交按钮禁用
- php - PHP:日期变化的增量变量