首页 > 解决方案 > 未实例化类的接口

问题描述

我有这样的代码结构:

interface ITool {
  repair(): void;
}

type HandlersMap = Map<string, ITool>;

abstract class AbstractTool {

  constructor(protected qpr, protected ctx) { }

  abstract async repair(): Promise<void>
}

class DebugTool extends AbstractTool implements ITool {
  async repair(): Promise<void> {
    this.logger.info(`Repaired item: ${this.qpr.type}`);
  }
}

class ToolFactory {
  private handlersMap: HandlersMap = new Map([
    ['debug-message', DebugTool]
  ]);

  createTool(type: string): ITool {
    ...
  }
}

导致错误:

handlersMap:“typeof DebugTool”类型中缺少属性“repair”,但在“ITool”类型中是必需的。

我知道这是因为我没有将类实例化为 Map 的值,但仍然实现了我引用的接口。有什么问题,我应该使用哪个接口来获取 Map 的值?

标签: typescript

解决方案


类似于以下内容:

type HandlersMap = Map<string, { new(...args): ITool }>;

如果您对构造函数参数有更多了解,则可以更具体(例如,如果所有工具都有参数qpr并且ctx您可以使用它而不是 variadic ...args)。


推荐阅读