简体   繁体   English

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

[英]How can I prevent typescript from throwing errors on an object that references another object's method

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

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 ): 解决方案可以是为包含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();

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: 编辑:在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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM