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



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

  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'.

解决方案可以是为包含addComponent方法但还接受任何其他附加属性的实体创建接口(请参阅允许其他属性的typescript界面(:

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

最新更新