Skip to content

Instantly share code, notes, and snippets.

@mtaran-google
Created July 12, 2018 19:11
Show Gist options
  • Save mtaran-google/8f30d4853e225e830d9a3e712eb96618 to your computer and use it in GitHub Desktop.
Save mtaran-google/8f30d4853e225e830d9a3e712eb96618 to your computer and use it in GitHub Desktop.
an ofType() implementation that propagates types better
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