Skip to content

Instantly share code, notes, and snippets.

@typoerr
Created January 28, 2018 04:32
Show Gist options
  • Save typoerr/ba121d0be548b298bf2c9cad1ec98a07 to your computer and use it in GitHub Desktop.
Save typoerr/ba121d0be548b298bf2c9cad1ec98a07 to your computer and use it in GitHub Desktop.
typed rxjs/operator/pluck
import { Observable } from 'rxjs/Observable'
import { of } from 'rxjs/observable/of'
import { map } from 'rxjs/operators'
/**
* Typesafe rxjs/operators/plunk
* @example
* const state$ = of({ counter: { count: 0 } })
* state$.pipe(getIn('counter', 'count')) //-> Observable<number>
*/
export function getIn<K extends string>(k: K)
: <T extends {[P in K]?: T[P]}>(src$: Observable<T>) => Observable<T[K]>
export function getIn<K1 extends string, K2 extends string>(k: K1, k2: K2)
: <T extends {[P1 in K1]: {[P2 in K2]: T[P1][P2]}}>(src$: Observable<T>) => Observable<T[K1][K2]>
export function getIn<K1 extends string, K2 extends string, K3 extends string>(k: K1, k2: K2, K3: K3)
: <T extends {[P1 in K1]: {[P2 in K2]: {[P3 in K3]: T[P1][P2][P3]}}}>(src$: Observable<T>) => Observable<T[K1][K2][K3]>
export function getIn(...path: string[]) {
return (src$: Observable<any>) => {
try {
return src$.pipe(map((src: any) => path.reduce((acc, k) => acc[k], src)))
} catch (e) {
return of(undefined)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment