Conditionally calling property/methods on classes

走远了吗. 提交于 2019-12-25 10:55:55

问题


I have a custom Array type class in Typescript. I didn't extend it because of the difficulties that comes with that, so I just use a private array which I have to directly reference each time I want to use an array method.

export class ObjectCollection<T extends ICollection> {

  public _Collection: T;
  public get Collection(): T {
    return this._Collection;
  }
  public getInstance: (id: string) => IListItem;

  constructor(collection: T) {
    this._Collection = collection;

    // used for getting instance from a collection of objects
    this.getInstance = (id: string): IListItem => {
      let instance = new Array<IListItem>();
      instance = this.Collection.filter(item => item.Id.toString() === 
      id.toString());

      if (instance && instance.length > 0) {
        return instance[0];
      }

      return new Object as IListItem;
    };

  }

}

If I want to call getInstance from the object, I could use newobjectinstance.getInstance(). If I wanted to use .map or native array functions, then I'd have to call newobjectinstance.Collection.map().

It would be a lot cleaner if I could just call newobjectinstance.map() or newobjectinstance.length. How could I change my code so that this would be possible?

I took a brief look at proxies, but couldn't figure out how to use them in this case. It's not an optimal solution because it is a react app, and proxies do not get transpiled by babel easily. If it's the only option, I'll try and fit it in, but any other suggestions would make me happy.

来源:https://stackoverflow.com/questions/46123916/conditionally-calling-property-methods-on-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!