打字稿:如何定义产生可调用实例的类

时间:2018-07-31 06:36:33

标签: 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()"

1 个答案:

答案 0 :(得分:2)

最简单的解决方案是使用接口类合并,并使用具有可调用签名的相同名称声明一个接口。结果类型将具有由接口和类定义的成员:

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()"