Enhance your React components with TypeScript Records

Adél
2 min readMar 2, 2022

--

One of the things I love about TypeScript is that it’s easy to start with and gradually make your code cleaner, more developer friendly and type-safe as you learn. Here’s one of my favourite tricks.

‘switch’ statements are far from popular in the developer world, but is it any better to write endless ‘if’ statements?

Imagine the scenario where you have a bunch of statuses and want to render a different component according to a given status. You might start out with something like the following:

React component with if statements

This is all fine and dandy, but let’s say that a few months later there is a new status you need to handle. You add the new status to your enum and nothing breaks.

Shouldn’t it though? 🤔

Your ‘switch’ statement will return the default HappyComponent for the newly added “mesmerized” status. You never meant for the HappyComponent to be some sort of silent default. You also have some colors and icons set for each status somewhere else in the code… 😞

👋 Meet TypeScript utility type - Record<Keys, Type>

Records are essentially typed objects. You have control over the type of the keys and values of the object.

Let’s rework our previous component a bit:

React Component with TypeScript Record

What did we gain with this?

  • TypeScript will error when a Record’s key type is missing, so you can rest assured that any time someone (or your later self) adds a new status to the status enum, all corresponding Records will have to be updated
  • Some code editors (e.g. WebStorm) will autogenerate a Record’s fields based on its declared types
  • no implicit default
  • cleaner code 🌟

WDYT? How do you usually go about this kind of problem? Any other neat trick up your sleeve? Would love to hear ;)

--

--

Adél

Web developer with a keen eye for graphic and motion design.