For this to function properly, you will need to provide a value of type K
at runtime. If I have grasped the concept of your Collection
class correctly, both an actual array of type T
and a value of type K
are required. The best way to obtain these values is during the construction of a new instance of Collection
. Therefore, it is recommended to have the constructor accept these as parameters:
class Collection<T, K extends keyof T> {
private _items: T[];
private _idKey: K;
constructor(items: T[], idKey: K) {
this._items = items;
this._idKey = idKey;
}
public isItemInCollection(item: T) {
return (
this._items.find(a => a[this._idKey] === item[this._idKey]) !== undefined
);
}
}
With this setup, you can proceed with usage as expected (assuming no details were provided about your specific use case). Taking into account the following types and objects:
interface MyItem {
idField: string;
otherField: number;
}
const itemA: MyItem = { idField: "A", otherField: 1 };
const itemB: MyItem = { idField: "B", otherField: 2 };
const itemC: MyItem = { idField: "C", otherField: 3 };
const items: MyItem[] = [itemA, itemB];
You can initialize a new Collection
:
const itemCollection = new Collection(items, "idField");
From type inference, it can be deduced that itemCollection
is of type
Collection<MyItem, "idField">
. Further interactions include:
console.log(itemCollection.isItemInCollection(itemA)); // true
console.log(itemCollection.isItemInCollection(itemC)); // false
console.log(
itemCollection.isItemInCollection({ idField: "A", otherField: 2893 })
); // Be cautious, result is true
Hopefully, this explanation clarifies things for you. Best of luck!
Link to code