首页 文章

Typescript:如何定义生成可调用实例的类

提问于
浏览
3

我目前正在将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 回答

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

相关问题