0

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.

  • 1
    hey @Stuart - I don't see a question in there. At least no question marks. – spottedmahn Sep 08 '17 at 20:49
  • Why do you declare a function inside the constructor? Why don't you use types? Why do you use `getInstance` ? It looks like a singleton pattern without using static. Why would you return a `new Object as IListItem`... In other words, please describe better what you expect your code to do and what is going wrong... – Kokodoko Sep 09 '17 at 12:25

0 Answers0