Skip to content

Instantly share code, notes, and snippets.

@captain-yossarian
Last active June 13, 2019 16:22
Show Gist options
  • Save captain-yossarian/c5631d1fc7d847fa7116d16e7ab4f113 to your computer and use it in GitHub Desktop.
Save captain-yossarian/c5631d1fc7d847fa7116d16e7ab4f113 to your computer and use it in GitHub Desktop.
TS Redux action factory
import { Action } from 'redux';
export enum Constants {
ACTION_NAMESPACE = 'ACTION_NAMESPACE',
}
export type ActionPayload<T, P> = Action<T> & { payload: P };
interface IPayload{
id: string;
mode: Modes;
}
type AllValues<T> = { [P in keyof T]: P extends Constants ? T[P] : null }[keyof T];
export interface IActionMap {
[Constants.ACTION_NAMESPACE]: IPayload;
}
export type AllActionsPayload = AllValues<IActionMap>;
type TypeTest<T> = keyof T extends Constants ? true : false;
/**
* @test
* if `unitTest` will be highlighted by red color, @interface IActionMap is not correct
*/
const unitTest: TypeTest<IActionMap> = true;
export const createAction = <T extends keyof IActionMap>(type: T) => (
payload: IActionMap[T]
): Action<T> & { payload: IActionMap[T] } => ({
type,
payload,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment