Post banner

Using TypeScript in React - Part 1: Basic Things

7 min read
Table of Contents

If you’re new to TypeScript and React, don’t worry! This guide will walk you through the basics and help you get started smoothly.

Quick intro to TypeScript

Basic Value Types

Simply put, TypeScript is a statically typed language. This means you need to specify types for the variables you use in your code.

Here’s a basic example of how to use type in your code.

const aNumber : number = 1
const aString : string = 'string'
const aBoolean: boolean = false
const anObject: object = { a: 1, b: 2 }
const anArrayOfStrings : string[] = ['a', 'b', 'c']
const anArrayOfNumbers : number[] = [1, 2, 3]
const anArrayOfObjects : object[] = [ { a: 1 }, { a : 2} ]

As you can see, some basic types that you can use include simple things such as:

  • number: denoting type for number value
  • string: denoting type for string value
  • boolean: denoting type for boolean
  • [] or Array : denoting type for array value

Custom Object Types

You can also create a specific type for an object to represent data in your app. Let’s say for example, a user in your React app might have these data:

  • First Name
  • Last Name
  • Email
  • URL Photo
  • Age

You can create a custom type for user easily like this:

type User = {
   firstName: string 
   lastName: string 
   email: string 
   urlPhoto: string
   age: number
}

You can also nest custom types under another custom type for creating more complex objects. Let’s say you are creating an E-Commerce application. Your app might have the following nested data:

  • User
    • First Name
    • Last Name
    • Email
    • URL Photo
    • Age
  • Product
    • Product Id
    • Product Name
    • Product Description
    • Quantity
    • Price
    • Currency
  • Cart
    • Products

We can represent that complex app data object with custom type with the following steps:

  • Create custom type for `User Profile
type User = {
	firstName: string 
    lastName: string 
    email: string 
    urlPhoto: string 
    age: number
}
  • Create custom type for Product object
type Product = {
	id: string 
	name: string 
	description: string 
	quantity: number 
	price: number 
	currency: string		
}
  • Create custom type for Cart object
type Cart = {
	products: Product[]
}
  • Then finally, let’s build the complete AppData object type
type AppData = {
	user: User
	cart: Cart
}

As you can see, building complex object types with TypeScript is very similar to how you build things with Lego. You start with the smallest possible things, then using those small things to construct a more complex object types.

Basic Function Types

We can also define a function contract with TypeScript if we know what is the input & output of the functions, but not sure yet how it should be implemented.

For example, let’s define a function that take a string, process it, then return a formatted value. We can define the function type as follows:

type StringFormatter = (text: string) => string

This type reads:

ℹ️

Given an input string, this function will return string as its output

The type can be used to build multiple string formatters later. For example:

const capitalizeFirst : StringFormatter = (text: string) => {
	const capitalizedFirstWord = .... // do logics in here
	return capitalizedFirstWord
}

const getInitialName: StringFormatter = (text: string) => {
	return text.charAt(0)
}

Now, there are obviously more complex types out there. But for now, what we’ve learned so far is enough. Let’s move on to how to use it in React.

Using TypeScript Types in React

Types are usually used to type component props in React. As you might know, props or short for properties are how a React component accepts data from the outside.

Planning a React Component

Let’s say you are building a Product Card component in an E-Commerce store. Image below shows how the Product Card component might look like in real-app.

Product List UI

The beauty of TypeScript is that, before we even begin building the component and write down the React codes, we are forced to think about how the data for that component should be structured.

For the E-Commerce screen we have above, we can identify that there are two main components for displaying products, namely:

  • Product Card: card for showing a single product
  • Product List: list of Product Card structured in a grid-layout

To simplify our discussion, let’s focus on breaking down the Product Card component first. From the UI, we can see that it needs the following data:

  • Product Id (i.e., to differentiate similar products)
  • Discount Rate
  • Product Name
  • Product Image
  • Review Stars
  • Number of Review
  • Benefits (e.g., Fast Delivery, Best Price, etc)
  • Price
  • Currency
  • isFavorite

Other than data, we need to have several event handlers to handle action on the product card itself. These are

  • onClickFavorite
  • onClickAddToCart

There is another action for handling the eye thing. But for now, let’s just ignore it for simplification.

Building the Types & Props

With the previous breakdown, we can create a data type for the Product card as follows:

export type Product = {
	id: string
	name: string 
	imageUrl: string
	stars: number
	reviewCount: number
	benefits: string[]
	price: number
	price: number 
	currency: string	
	isFavorite: boolean
}

Then, we can define the props for the ProductCard component with the combination of the Product data and also the event handler types as follows:

export type ProductCardProps = {
	product: Product
	onClickFavorite: (id: string) => void
	onClickAddToCart: (product: Product) => void
}

Here are some key things to understand:

  • The type void means the function will not return anything after it finishes the executions.
  • We export the types since it might be used in other places of the codes to build the product or the props. For example ProductCardProps will be needed when we build the ProductList component.

Using Typed Props in Component

Then, we can use and destructures the props in our component creation as follows

export default function ProductCard({
	id,
	name,
	imageUrl,
	stars,
	reviewCount,
	benefits,
	price,
	currency,
	isFavorite
}: ProductCardProps) {
   // component structure codes in JSX
}

You will get type hint if you are using editors such as VSCode, Cursor, etc.

Closing

Obviously, there are more advanced use cases for types in React. But with everything we have learned so far, I can say you are 70% understand how TypeScript should be use in React projects.

Most advanced types are about custom types. There are a lot of them, but each one of them are actually built with the small building blocks like I’ve mentioned before.

With all the explanations so far, I hope you get courage to start using TypeScript and enjoy a more error-free code in your projects!

I’ll write more advanced topics later.

Thanks for reading 😊

ℹ️

P.S:

You can use Online TypeScript Playground to test out examples.