我目前正在将 JS 类转换为 TypeScript。该类扩展自 NPM 模块节点可调用实例 https://www.npmjs.com/package/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()"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)