Created
July 12, 2018 19:11
-
-
Save mtaran-google/8f30d4853e225e830d9a3e712eb96618 to your computer and use it in GitHub Desktop.
an ofType() implementation that propagates types better
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Action} from '@ngrx/store'; // from //third_party/javascript/ngrx:ngrx_store | |
import {OperatorFunction} from 'rxjs'; | |
import {filter} from 'rxjs/operators'; | |
// Removes types from T that are not assignable to U. | |
export type Filter<T, U> = T extends U ? T : never; | |
/** | |
* Equivalent to the `ofType` operator provided by @ngrx/effects, but with | |
* smarter type inference. | |
* | |
* Type propagation currently scales to five input strings. | |
* | |
* See https://github.com/ngrx/platform/blob/master/docs/effects/api.md#oftype | |
*/ | |
export function ofType< | |
T1 extends string, U extends Action, V extends Filter<U, {type: T1}>>( | |
t1: T1, | |
): OperatorFunction<U, V>; | |
export function ofType<T1 extends string, T2 extends string, U extends | |
Action, V extends Filter<U, {type: T1 | T2}>>( | |
t1: T1, | |
t2: T2, | |
): OperatorFunction<U, V>; | |
export function | |
ofType<T1 extends string, T2 extends string, T3 extends string, U extends | |
Action, V extends Filter<U, {type: T1 | T2 | T3}>>( | |
t1: T1, | |
t2: T2, | |
t3: T3, | |
): OperatorFunction<U, V>; | |
export function ofType<T1 extends string, T2 extends string, T3 extends | |
string, T4 extends string, U extends Action, V | |
extends Filter<U, {type: T1 | T2 | T3 | T4}>>( | |
t1: T1, | |
t2: T2, | |
t3: T3, | |
t4: T4, | |
): OperatorFunction<U, V>; | |
export function | |
ofType<T1 extends string, T2 extends string, T3 extends string, T4 extends | |
string, T5 extends string, U extends Action, V extends | |
Filter<U, {type: T1 | T2 | T3 | T4 | T5}>>( | |
t1: T1, | |
t2: T2, | |
t3: T3, | |
t4: T4, | |
t5: T5, | |
): OperatorFunction<U, V>; | |
export function ofType<U extends Action>(...allowedTypes: string[]): | |
OperatorFunction<U, U> { | |
return filter( | |
(action: U): boolean => allowedTypes.some(type => type === action.type)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment