【问题标题】:How to declare Map from constructor (key) and class instance (value) in Typescript?如何在 Typescript 中从构造函数(键)和类实例(值)声明 Map?
【发布时间】:2016-02-03 20:09:52
【问题描述】:

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

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

如何声明 Map 其中 key = Class 构造函数,value = Class 实例?

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);
  }
}

【问题讨论】:

    标签: dictionary constructor typescript


    【解决方案1】:

    构造函数是一个函数,所以你可以这样写:

    declare type MapOfComponents = Map<Function, Component>
    

    【讨论】:

    • 马丁,谢谢。这是工作。我知道,不一定,但是否可以声明 MapOfComponents 让 entity = new Entity();功能测试() {};函数 A(a) { this.a } 让 a = new A(1); entity.components.set(test, a);会产生错误(a 不是测试实例)?
    • 如果您的意思是编译时错误,那么您可以使用联合类型:declare type MapOfComponents = Map&lt;Function, OneComponent | SecondComponent | ThirdComponent&gt; ...但我认为您不会喜欢它。如果你的意思是运行时错误,那么你可以使用if (!(a instanceof Component)) { /* report error */}
    • 是的,谢谢!我对 tsc 和 tslint 有一些问题。如何更改文件的 tslint 规则?我需要在一个文件中使用 qoutemark single insted double。我怎么能这样做 /* tslint qoutemakr: double*/?
    • 如果它解决了你的问题,你能接受这个答案吗?
    • 和 tsc。 tss 在 lib.core.es6.d.ts 中没有任何警告或异常,但 tsc 总是有这样的句子错误:[Symbol.toStringTag]: "Symbol";
    猜你喜欢
    • 1970-01-01
    • 2020-09-13
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    • 2017-06-02
    • 2016-05-16
    • 2015-03-01
    相关资源
    最近更新 更多