Skip to content

Instantly share code, notes, and snippets.

@MikuroXina
Last active March 5, 2026 06:58
Show Gist options
  • Select an option

  • Save MikuroXina/ba82959d015ca8269098e88844ffc1d3 to your computer and use it in GitHub Desktop.

Select an option

Save MikuroXina/ba82959d015ca8269098e88844ffc1d3 to your computer and use it in GitHub Desktop.
The template for creating a custom reducer.
export interface State {
/* Type your state definition. */
}
export const initialState = (): State => ({
/* Type your initial state. */
});
const reducers = {
/* Type your reducer by key of the action name. */
HELLO: (state: State, _action: {}) => state,
} as const;
type Reducers = typeof reducers;
type Payload<K extends keyof Reducers> = Reducers[K] extends (
state: State,
action: infer A
) => State
? A
: never;
export type Action = {
[K in keyof Reducers]: [K, Payload<K>];
}[keyof Reducers];
export type Dispatcher = (action: Action) => void;
export const reducer = (
state: State,
[kind, payload]: Action,
): State => reducers[kind](state, payload as Payload<typeof kind>);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment