Tips for typing React components with TypeScript

Maciek Wątroba
JavaScript in Plain English
3 min readMar 5, 2021

--

I love TypeScript. I consider it to be a best practise when setting up a new React project (even a simple one!). It is a great tool for improving developers’ productivity and avoiding some bugs. Getting started is easy, both create-react-app and nextjs come with built-in support.

In this article I’m going to demonstrate some techniques that you can use in your day to day work with TypeScript and React. Let’s get started!

Use union types

Whenever a given prop can accept a constrained set of values using union types is a good idea. Let’s say you want to create a Text component that accepts a size prop. The initial idea may be to type it as a string, but we can do better. Let’s see an example.

Now we can be sure size can only accept any of those 3 values. As a bonus we get autocompletion support (assuming we use VSCode or any other IDE with good TS support)

here I actually use codesandbox.io

Also we can avoid using constants like TEXT_SIZE.SMALL which I personally find ugly.

Do not repeat yourself

As we are happy with union types we decided to write the actual implementation. We used a simple object to define font sizes.

Now we have a problem. We need to update size prop type definition every time we change sizes object. Let’s see how we can fix it withkeyof operator.

Awesome, this is much more DRY! To introduce an additional size all we need to do is update sizes object.

Use generics

Let’s say we want to build a generic list view component. I like to first think about the interface. Let’s say we want to accept an array of items and a renderer function (this is known as render prop pattern).

Well, that works but is far from perfect. There is no guarantee on type level that renderItem function is able to render provided items. Let’s see how we can make this code better using generic.

Great! We tied items type with renderItem function signature. Now let’s analyse a complete code example

A couple of things to notice:

  1. We can be sure that renderItem function accepts an item from items array (check yourself and try to break it!)
  2. We use generic constraints to make sure every item has uuid property (this is important so we can provide key prop that react needs when rendering a list)
  3. Our ListView doesn’t care what kind of items we render as long as we can provide a function to render a single item.

Summary

Thanks for reading! I hope you found something new you can apply in your day-to-day work. Remember, practise is everything. Happy coding!

--

--