DEV Community

wshi9124
wshi9124

Posted on

TypeScript with React

Set up React TypeScript project:
npx create-react-app app-name --template typescript

Add TypeScript to existing React App:
npm install --save typescript @types/node @types/react @types/react-dom @types/jest

Notice that instead of js files, we have tsx files instead.
Image description

As a review, here is how we declare types in TypeScript
-let age: number | string means that age can be either a number or string (union type)
-let hobbies:string[] means that the array can only contain strings
-let role:[number,string] means that the array can only contain one number and one string
-for objects we need to declare a type or interface keyword
-? makes age property optional
-let lotsOfPeople:Person[] means that we want an array of Person object
Image description
Function Types
-void means that there is an absence of any type at all
-you should use unknown instead of any type if you don't know what type it is going to be
Image description
Aliases(type and interface)

  • in the image below both type and interface mean the same thing. Keep in mind that there is no = for interface Image description -A difference between type and interface is way they extend -you can extend between type and interface Image description Image description

Now that the review is over, lets get into React with TypeScript

UseState
you can declare type if state with <>. However, you do not really need to specify if there is only one type. It is better for TypeScript to infer what type it is.
Image description

Props
There are 2 ways to pass down props in React
However, you should always make an interface first
-Notice that you can find out what type setNumber is by hovering over it
Image description
Image description
Image description
Functions
You can set what type you want the function to return by putting a : after the ().
-Hint- if you don't know what type the function is, you can hover over the name once you complete writing the function.
Image description
Handling events
when handling onClick the type for e is
$React.ChangeEvent< HTMLInputElement | HTMLTextAreaElement >
HTMLInputElement is for inputs
HTMLTextAreaElement is for text area
when handling onSubmit the type for e is
$React.FormEvent
Once again if you can't figure out the type you can hover over the name of the function
Importing interfaces
One way to make code more dry is to import interfaces
the syntax is:
import { InterfaceYouWantToImport as NewNameOfInterface} from "location"

Now that you have the basics of TypeScript with React, you can start incorporating TypeScript to your own React projects!

References:
https://www.typescriptlang.org/docs/handbook/intro.html
https://www.youtube.com/watch?v=jrKcJxF0lAU&t=898s&ab_channel=PedroTech
https://www.youtube.com/watch?v=FJDVKeh7RJI&t=151s&ab_channel=freeCodeCamp.org

Top comments (0)