I'm tying to create a re-usable function that takes an observable and returns observable after a few operators are applied.
However, I can't get the value
to be the correct type depending on key
used. The code below gives me an error with typeof keyof T
getByKey<T extends BasicApiResponse>(data: Observable<T[]>, key: keyof T, value: typeof keyof T): Observable<T> {
return data.pipe(
filter((items) => !!items),
map((items) => items.find((e) => e[key] === value)),
filter((item) => !!item),
distinctUntilChanged((prev, curr) => isEqual(prev, curr))
);
}
example:
const obs = of([{ id: 'item-1', index: 2 }])
getByKey(obs, 'id', 'item-1' ); // should work as expected.
getByKey(obs, 'index', '2' ); // should error as it needs to be a number not string.
CodePudding user response:
You need to add a type parameter for teh key passed in as an argument. This will allow you to capture the type of the key being passed in. Then you can use an indexed type to get the type of the property (T[K]
)
function getByKey<T extends BasicApiResponse, K extends keyof T>(data: Observable<T[]>, key: K, value: T[K]): Observable<T> {
return data.pipe(
filter((items) => !!items),
map((items) => items.find((e) => e[key] === value)),
filter((item) => !!item),
distinctUntilChanged((prev, curr) => isEqual(prev, curr))
);
}