Software
January 3, 2023

How to Use Typescript React Props with PropTypes?

An easy and scalable way to use Typescript prop checking with React PropTypes

Introduction

You might be working on a React app that’s built using Typescript and need to support PropTypes. Why would you need both of them? Well, each solution serves a different purpose. PropTypes are checked at runtime while Typescript validates types at compilation time.

In my case, I was working on a React UI library that was built using Typescript. But most consumers of that library in my company are still using Javascript. So in a lot of cases, the export Typescript props are not enough to mitigate passing the wrong data to the component, hence why we need PropTypes as well.

Requirements

First of all, you need to be working on a Typescript React project and have the following packages installed:

npm install prop-typesnpm install -D @types/prop-types

The Problem

The first solution that pops into the head is to create the PropTypes manually, but the problem with that is we need to manually sync it with the Interface Props, which can be a pain and error-prone.

We need an easy and straightforward way to force compilation checks that makes sure our PropTypes definition matches the Interface Props. Essentially we will only have one source of truth for our props definition.

Solution

The best solution I found was to generate a PropTypes Map from the Props Interface itself. This might sound confusing at first, so let me demonstrate.

Let’s say we have a component called Foo:

We will use ValidationMap to generate the Typescript interface map for PropTypes like the following

You can find here a much more complex example.

Conclusion

If you have any questions please leave a comment and will try to respond as soon as I can.

If this was helpful to you make sure to subscribe to the newsletter for more React/Typescript tips and like this post! Thank you!