如何防止打字稿在引用另一个对象方法的对象上引发错误

时间:2019-07-07 15:25:32

标签: javascript typescript

所以我有一个实体组件系统,基本上,当您将一个组件对象添加到实体时,它会将所有方法绑定到该实体对象。

  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:() TS2339: Property 'componentMethod' does not exist on type 'Entity'.

1 个答案:

答案 0 :(得分:1)

一种解决方案可以是为包含addComponent方法但还接受任何其他附加属性(请参见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();

编辑: 在TypeScript的最新版本中,您无需通过接口,并且可以通过如下修改Entity类来做到这一点:

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