Answer the question
In order to leave comments, you need to log in
How in ts to distribute the fields of an object into another object?
export default interface IComponent {
name: string;
};
export interface IComponentsList {
[key: string]: IComponent;
}
export interface IComponents {
health: IHealth[];
}
class Entity implements IEntity {
readonly id: string = '';
components: IComponentsList = {};
}
class Main {
components: IComponents = {
health: [],
};
entities: Map<string, IEntity> = new Map();
addEntity(entity: IEntity) {
for ( let componentKey in entity.components ) {
if (entity.components.hasOwnProperty(componentKey)) {
this.components[componentKey].push(entity.components[componentKey]);
}
}
}
}
Answer the question
In order to leave comments, you need to log in
IComponentsList according to your description can contain any property.
and you push it to IComponents, in which you want a "strict" description. This is a type mismatch and a potential bug from which the compiler honestly protects you - otherwise, in your runtime in components in Main, it may not be what is written in the types.
the most correct would be to add an index signature to IComponents.
But if you're confident and want the compiler to believe you, you can do the following:
or
or somehow suppress the compiler at this point.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question