typescript - 打字稿:如何定义一个产生可调用实例的类
问题描述
我目前正在将 JS 类转换为 TypeScript。该类从 NPM 模块node-callable-instance扩展而来(这使得它在内部成为 Function 的子类)。类的实例可以像函数一样被调用。简短的例子:
import * as CallableInstance from "callable-instance";
class MyClass extends CallableInstance {
constructor() { super('method'); }
method(msg) { console.log(msg); }
}
const inst = new MyClass();
inst('test'); // call will be forwarded to "method()"
这些实例是可调用的,这是该特殊项目的要求,其他构建时工具依赖于此。
有没有办法在 TypeScript 中表达它?上面的代码给出
错误 TS2349:无法调用其类型缺少调用签名的表达式。类型“MyClass”没有兼容的调用签名。
我第一次尝试通过使用可调用接口来解决这个问题失败了,因为该类没有实现调用签名......
import * as CallableInstance from "callable-instance";
interface MyClassCallable {
(msg: string): void;
}
class MyClass extends CallableInstance implements MyClassCallable {
constructor() { super('method'); }
method(msg: string): void { console.log(msg); }
}
const inst = new MyClass();
inst('test'); // call will be forwarded to "method()"
解决方案
最简单的解决方案是使用接口类合并并声明一个具有可调用签名的同名接口。结果类型将具有由接口和类定义的成员:
import * as CallableInstance from "callable-instance";
class MyClass extends CallableInstance {
constructor() { super('method'); }
method(msg: string): void { console.log(msg); }
}
interface MyClass {
(name: string): void
}
const inst = new MyClass();
inst('test'); // call will be forwarded to "method()"
推荐阅读
- json - Logstash:如何将多行 json 对象和 add_field 拆分为 kibana?
- javascript - 如何允许机器人在我的保管箱上创建文件/附加文件
- laravel - Laravel Eloquent:如何在 WithCount 中使用“where”来选择计数大于数字的模型
- python - 如果值包含 \u000b,则在我使用 openpyxl 时发生 IllegalCharacterError
- javascript - Meteor/React 中的异步代码到嵌套同步方式
- python - 使用 Keras 设计 CNN:了解张量形状
- java - 如何使用单个 for 循环执行多个数组操作?
- inno-setup - 如何使用 Inno Setup 设置短暂的延迟?
- selenium - 当 selenium 中没有与同一 webelement 关联的定位器时如何查找 webelement
- python - JSON数据是Flask中的字符串还是字典?