DEV Community

James
James

Posted on • Edited on

1

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)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay