簡體   English   中英

如何從Typescript中的構造函數(鍵)和類實例(值)聲明Map?

[英]How to declare Map from constructor (key) and class instance (value) in Typescript?

以下代碼具有component.constructor(實體構造函數以及addComponent和removeComponent方法)錯誤。

錯誤:不能將類型為“功能”的參數分配給類型為“ typeof Component”的參數。

如何聲明Map,其中key =類構造函數,值=類實例?

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

構造函數是一個函數,因此您可以編寫:

declare type MapOfComponents = Map<Function, Component>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM