问题
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