I am currently working on developing a reusable function that takes an observable and applies various operators to return another observable.
One issue I am facing is getting the correct type for the value
based on the use of the key
. The code snippet below throws 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' ); // This should work as expected.
getByKey(obs, 'index', '2' ); // This should result in an error since a number is expected instead of a string.