1 min readSep 26, 2019
Great article.
I have used this approach to create a custom RxJS operator to use in Angular with HttpClient
When I receive an array of User, from an HTTP request, my custom RxJS operator can pass, as argument, one of the key of User, that must be a number and, of course, exist on User.
This is how I use the operator:
this.http.get<User[]>(‘https://jsonplaceholder.typicode.com/users'
// 'qty' must be a number and exists on User
.pipe(sumProps(‘qty’))
and that’s a simplified version of the operator where I use the conditional type:
type SubType<T, Condition> = Pick<T, {
[Key in keyof T]: T[Key] extends Condition ? Key : never
}[keyof T]>;const sumProps =
<T, K extends keyof SubType<T, number>>(propertyName: K)
:OperatorFunction<T[], number> => {return input$ => input$.pipe(
switchMap(res => res),
reduce((acc: number, user: T) => {
return acc + +user[propertyName];
}, 0)
)}
Thank you very much
Fabio