首页 > 解决方案 > 打字稿:如何定义一个产生可调用实例的类

问题描述

我目前正在将 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()"

标签: typescript

解决方案


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

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

推荐阅读