Skip to content

Instantly share code, notes, and snippets.

@dvitiuk-opensource
Last active June 8, 2018 10:24
Show Gist options
  • Save dvitiuk-opensource/9ef143411b2fa5078d31f1463c98105e to your computer and use it in GitHub Desktop.
Save dvitiuk-opensource/9ef143411b2fa5078d31f1463c98105e to your computer and use it in GitHub Desktop.
Improved NgRx type safety with TypeScript 2.8
type FunctionType = (...args: any[]) => any;
interface ActionCreatorsMapObject {
[action: string]: FunctionType;
}
export type ActionsUnion<A extends ActionCreatorsMapObject> = ReturnType<A[keyof A]>;
export interface Action<T extends string> {
type: T;
}
export interface ActionWithPayload<T extends string, P> extends Action<T> {
payload: P;
}
export function createAction<T extends string>(type: T): Action<T>;
export function createAction<T extends string, P>(type: T, payload: P): ActionWithPayload<T, P>;
export function createAction<T extends string, P>(type: T, payload?: P) {
return payload === undefined ? {type} : {type, payload};
}
// https://github.com/ngrx/platform/issues/860
type ActionsOfType<A, T extends string> = A extends Action<T> ? A : never;
export function ofType28<V, T1 extends string>(t1: T1): OperatorFunction<V, ActionsOfType<V, T1>>;
export function ofType28(...types: string[]) {
return (source: Observable<any>) => {
return source.pipe(filter((action) => types.indexOf(action.type) !== -1)) as any;
};
}
// DO NOT USE ON PRODUCTION
// import {Action} from '@ngrx/store';
//
// declare module "@ngrx/store" {
// export interface Action<T extends string = string> {
// type: T;
// }
// }
//
// declare module "@ngrx/effects" {
// export function ofType<V, T1 extends string>(t1: T1): OperatorFunction<V, ActionsOfType<V, T1>>;
// }
// T extends U ? X : Y
type TypeName<T> =
T extends string ? "string" :
T extends number ? "number" :
T extends boolean ? "boolean" :
T extends undefined ? "undefined" :
T extends Function ? "function" :
"object";
type T0 = TypeName<string>; // "string"
type T1 = TypeName<"a">; // "string"
type T2 = ReturnType<() => string>; // "string"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment