DEV Community

Cover image for TypeScript + React
Md Anas Sabah
Md Anas Sabah

Posted on

TypeScript + React

Why TypeScript + React

You all think why we need TypeScript when we are just happy creating React App using JavaScript. Now, I was at that stage as well but having used TypeScript for a while I can safely say that it has improved the overall development experience for me.

• With static type checking, you get to learn potential bugs as you're typing the code, than heading to the browser and figure out at run time.

• It also provides a way to describe the shape of an object hence providing better documentation and autocomplete.

• TypeScript even make maintenance and refactoring large code bases much easier.

As you can see there are some pretty good points to help you make the decision of adopting TypeScript.

Getting Started

Install create-react-app

create-react-app provides us a TypeScript template we can use:

create-react-app

Note: npx stands for Node Package Execute and it comes with the npm to excecute CLI command.

Now run the command npm start on your terminal. The command will open the browser on localhost:3000 with your basic react typescript application up and running.

In src folder, we see index.tsx and an app.tsx file.
index.tsx
index.tsx is the entry point to our react app where we mount our app component onto the root DOM node

app.tsx
app.tsx contains our app component which is the root component

Function Component

To demonstrate a functional component with props we will create Greet Component. It will receive a prop "name" that will welcome the user.
function

While adding props in TypeScript you need to tell typescript what is the type of props you're passed in.
So, way to inform the type of props to typescript is by using "type" keyword.

props
Now a component props is an object so within Greetprops object the key will be name and data type is string.
To inform typescript about this, after props within parenthesis we specify colon and then type name(Greetprops).

Class Component

In class component, we will create Description component and in it we will create a counter. One of the key differences between a class and functional component is that a class component can maintain its own state.
description
In here, we declare a interface for both the CProps and CState. There will be an optional prop call countby which will determine the increment value.

And now Inside our App.tsx we import Description.tsx
count

That's all, I hope you found this article helpful.🙂

Top comments (1)

Collapse
 
ghazanfarofficial01 profile image
Ghazanfar Mumtaz

Great!!