Typescript in React

Learn how Typescript integration helps in a React application.

We'll cover the following

TypeScript for JavaScript and React have many benefits for developing robust applications. Instead of getting type errors on runtime in the command line or browser, TypeScript integration presents them during compile time inside the IDE. It shortens the feedback loop of JavaScript development. While it improves the developer experience, the code also becomes more self-documenting and readable, because every variable is defined with a type. Also moving code blocks or performing a larger refactoring of a code base becomes much more efficient. Statically typed languages like TypeScript are trending because of their benefits over dynamically typed languages like JavaScript. It’s useful to learn more about Typescript whenever possible.

To use TypeScript in React, install TypeScript and its dependencies into your application using the command line. If you run into obstacles, follow the official TypeScript installation instructions for create-react-app:

npm install --save typescript @types/node @types/react
npm install --save typescript @types/react-dom @types/jest

Next, rename all JavaScript files (.js) to TypeScript files (.tsx).

mv src/index.js src/index.tsx
mv src/App.js src/App.tsx

Restart your development server in the command line. You may encounter compile errors in the browser and IDE. If the latter doesn’t work, try installing a TypeScript plugin for your editor, or extension for your IDE. After the initial TypeScript in React setup, we’ll add type safety for the entire src/App.tsx file, starting with typing the arguments of the custom hook:

Get hands-on with 1200+ tech skills courses.