如何在Typescript中从构造函数(key)和类实例(value)声明Map?

时间:2016-02-03 20:09:53

标签: dictionary constructor typescript

以下代码与component.constructor(实体构造函数和addComponent以及removeComponent方法)有错误。

错误:类型'功能'的参数不能分配给' typeof Component'。

类型的参数

如何声明Map where key = Class构造函数,value = Class instance?

declare class Component {
  constructor(...argArray: any[]);
}

// declare type MapOfComponents = Map<{new(): Component}, Component>
declare type MapOfComponents = Map<typeof Component, Component>

export default class Entity {
  static id = 1;

  id: number;
  components: MapOfComponents = new Map();

  constructor(components?: Array<Object>) {
    this.id = Entity.id++;

    components.forEach((component) => {
      this.components.set(component.constructor, component);
    });
  }

  addComponent(component: Component): this {
    this.components.set(component.constructor, component);
    return this;
  }

  removeComponent(component: Component): this {
    this.components.delete(component.constructor);
    return this;
  }

  hasComponent(ctr: typeof Component): boolean {
    return !!this.components.get(ctr);
  }

  getComponent(ctr: typeof Component): Object {
    return this.components.get(ctr);
  }
}

1 个答案:

答案 0 :(得分:0)

构造函数是一个函数,因此您可以编写:

declare type MapOfComponents = Map<Function, Component>