D
D
Diamond2019-05-02 22:54:36
typescript
Diamond, 2019-05-02 22:54:36

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

There are entities, they can be many and different. Entities are a container object that contains a field with an id and an object with components.
Also, there is a Main class, which should collect all components from all entities.
The problem is that when trying to do this, an error appears: " Element implicitly has an 'any' type because type 'IComponents' has no index signature. " The error implies that " IComponents " needs to be recast to look like " IComponentsList ", but I need to leave a strict description of this interface.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2019-05-04
@Robur

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 question

Ask a Question

731 491 924 answers to any question