0

So I have an entity component system, and basically when you add a component object to an entity its binds all the methods to the entity object.

  class Component {
     constructor(){}
     componentMethod() {
       console.log('component method called');
     }
  }
  class Entity {
     constructor(){}
     addComponent(component) {
        Object.getOwnProperties(component).forEach(p => {
           // some logic make sure its not constructor or duplicate in entity
           this[p] = component[p].bind(component);
        })
     }
   }
   const component = new Component();
   const entity = new Entity();
   // works fine
   entity.addComponent(component);
   entity.componentMethod(); // works if I type entity as any but typescript is throwing an error when I type entity as Entity

Error

Error:() TS2339: Property 'componentMethod' does not exist on type 'Entity'.
Anshu
  • 1,277
  • 2
  • 13
  • 28

1 Answers1

0

A solution can be to create an interface for an entity that contains the addComponent method but accepts also any other additional attribute (see TypeScript interface that allows other properties):

...
interface IEntity {
    addComponent: Function;
    [x: string]: any;
}

const component = new Component();
const entity: IEntity = new Entity();
// works fine
entity.addComponent(component);
entity.componentMethod();

Edit: In the last versions of TypeScript, you do not need to go through an interface and can do the same by modifying the Entity class as follow:

class Entity {
    constructor(){}
    addComponent(component: any) {
        Object.getOwnProperties(component).forEach(p => {
           // some logic make sure its not constructor or duplicate in entity
           this[p] = component[p].bind(component);
        })
    }
    [x: string]: any; 
}
const component = new Component();
const entity = new Entity();
// works fine
entity.addComponent(component);
entity.componentMethod();
F. Bauer
  • 219
  • 2
  • 5