DEV Community

James
James

Posted on • Edited on

Typescript & reducer actions

I'm still learning Typescript. I like it, but sometimes it can feel like it's getting in the way. With React state reducers it seems all too easy to duplicate action types.

The following example tidies up the use of dispatch actions by taking an array of action names, creating a Union type from that array, and then creating an Action and Record type from that Union.

const actionsTypes = [
  'COMPONENT_STATE_VALID',
  'COMPONENT_STATE_LOADING',
  'COMPONENT_STATE_COMPLETE',
  ...
];

type ActionTypeUnion = typeof actionsTypes[number];
type Action = { type: ActionTypeUnion };
type Actions = Record<ActionTypeUnion, Action>;

const actions: Actions = actionsTypes.reduce(
  (acc, type) => ({ ...acc, [type]: { type } }),
  {},
);
Enter fullscreen mode Exit fullscreen mode

This is pretty concise and gives us great type support when implementing an action e.g. dispatch(actions.COMPONENT_STATE_VALID)

Top comments (0)