TypeScript and React
Welcome to this little primer on TypeScript and React! A match made in heaven!
With that, TypeScript and React are a perfect fit. You will enjoy combining both technologies together to get huge productivity boost when writing your applications!
This guide assumes that you are familiar with the basic concepts of both React and TypeScript. We will focus on the combination of the technologies and the resulting features.
Also, this guide does not claim to be complete. It’s one way and more important one easy way to dive into React and TypeScript, modelled after two core principles:
- Using as little setup and tools as possible. TypeScript already has a transpiler and a JSX compiler, so the only thing we need extra is some bundling. I will link to guides if your project needs some extra tooling.
- Using TypeScript features only where needed. TypeScript has brilliant type inference, so you get a ton of features like autocompletion and type safety already out of the box and without any extra code. Wherever we can improve on what’s given, we will.
Ready? Let’s go!
Last update: September 15, 2021
Table of contents: #
- Getting started: How to set up TypeScript and React, and what are your options
- Components: Components are everything in React. TypeScript gives you a lot of ways how to deal with them.
- Children: There’s nothing more beautiful than children. In React, they even can be functions.
- Events: Apps are boring if you don’t interact with them. Clicks, inputs, etc. are handled here.
- Prop Types: Prop Types are React’s built-in way of type checking. We can make good use of that with TypeScript.
- Hooks: Hooks are pretty new and pretty exciting. And already pretty well typed.
- Render props and child render props: A technique for sharing code between React components using a prop whose value is a function. We can type that!
- Context: React’s context API gives you global state with a very lean API.
- Styles: CSS in JS in lots of ways
- Further reading: So many things not covered in our guide. You will find them here.
Blog articles #
Next to this guide, I write regular blog articles that cover TypeScript. Occasionally, I also work on React related topics:
- JSX is syntactic sugar: On how TypeScript is a pure JSX compiler
- Extending JSX elements: How to extend pre-defined JSX elements with attributes that are not yet available in all browsers
- Typing custom hooks with tuple types: Tuple types are great for
useStatelike hook patterns
- Component patterns: Some component patterns, a sort of best practices guide
- Why I don’t use React.FC: An opinion on why I don’t use the built-in type
- Generic forwardRef: Using
React.forwardRef? Using generic components? Then you might run into typing troubles. This piece helps you out.
- Children types are broken. Maybe beyond repair. Here’s a little fix that can help you.