Using Create React App v2 and TypeScript

Now that Create React App v2 is out, official TypeScript support comes with it. This is an exciting thing for JavaScript users that use TypeScript. TypeScript is a powerful tool that helps us write safer and self-documenting code. We can catch bugs faster with TypeScript.

A JavaScript Component

A simple component where we pull message out of props. Now let's add some TypeScript to tell this function that it's message parameter should be a string:

Adding TypeScript

If you're familiar with TypeScript, you may think you want to add the following to message: message: string. What we have to do in this situation is define the types for all props as an object. There's a few ways we can do this:

Separate Types Object

There are many ways to use TypeScript in our projects. You can create an interface and move that into a separate file so your types can live elsewhere. This may seem like a lot of writing, so let's see what we gain for writing a bit more.

We've told this component that it only accept a string as the message parameter. Now let's try using this inside our App component.

My favorite part about TypeScript is that it let's us write self-documenting code.

When we go to use this component, we can see VS Code bring up the component's signature right as we type! We don't have to jump back to the component (especially if it's in another file) to see what its inputs should be.

Now that isn't the most readable, so let's jump into using each prop individually.

Seeing Prop Types

As soon as we start typing message, we can see what that prop should be:

Seeing Type Errors

If we add a number as message, TypeScript will throw an error and help us catch these typing bugs.

This only scratches the surface of what TypeScript provides us. You can create types for all your components and props and with VS Code, be able to read those easily. You'll also catch errors faster since TypeScript won't even let the project compile with type errors.