以下代码与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);
}
}
答案 0 :(得分:0)
构造函数是一个函数,因此您可以编写:
declare type MapOfComponents = Map<Function, Component>