DEV Community

AyomikeCharles
AyomikeCharles

Posted on • Edited on

Setting up Typescript in React

Introduction
React is a JavaScript library use for building user interface.

TypeScript is a syntactic superset of JavaScript, this means typeScript adds syntax on top of JavaScript.

in this tutorial, I will discuss how to set up typeScript in a react project.

Prerequisite
if you are familiar with React and the basic of typescript, you are good to go.
check out my typescript cheatsheet part 1 writeup here TypeScript Cheatsheet Part 1

Getting started

if you are starting a new react project,

ensure you have node and npm installed in your system.
first of all, open your terminal and create a folder to work in

mkdir Reat-typscript-setup
cd Reat-typscript-setup
Enter fullscreen mode Exit fullscreen mode

next, install your react typeScript project

npx create-react-app name-of-app --template typescript
Enter fullscreen mode Exit fullscreen mode

or

yarn create react-app name-of-app --template typescript
Enter fullscreen mode Exit fullscreen mode

its as simple as that, your react typeScript project should install and you are good to go.

if you already have an existing react project and you want to add typescript to the project, you simply install typeScript into the project. make sure you are in the project directory in you terminal, then install typeScript as seen below

npm install --save typescript @types/node @types/react @types/react-dom @types/jest
Enter fullscreen mode Exit fullscreen mode

or

yarn add typescript @types/node @types/react @types/react-dom @types/jest
Enter fullscreen mode Exit fullscreen mode

Finally, rename all javaScript file to be a TypeScript file (e.g. src/App.js to src/App.tsx) and restart your development server!

you now have a fully typeScript project, but some type errors show up in the same console as the build one, correct these errors and continue your development.

Enjoy typing.

Top comments (0)