Type Safety in React: An Introduction to TypeScript



April 19, 2023


April 19, 2023

Welcome to the fascinating world of React with TypeScript! If you've been working with React, you're probably familiar with its tremendous potential and adaptability. But have you ever wondered what would happen if you added type safety to it?

In this blog, we will introduce you to TypeScript, help you to get started with the React TypeScript project, walk you through the process of creating basic components, and explain why type safety in React is important. 

This will help you understand the benefits of using TypeScript with React and avoid the common pitfalls. So let's dive into the world of type safety in React!

Blog highlights: 

Introduction: React and TypeScript

What is TypeScript?

TypeScript is a superset of JavaScript that adds strict type binding to the language, making it easier to catch errors before they happen. TypeScript also provides all features of object-oriented programming, including classes and interfaces. 

Why use TypeScript with React?

When combined with React, TypeScript can help scale up medium to large-sized projects. Developers can create a new React app with TypeScript or convert an existing project to TypeScript. 

Using TypeScript in React projects offers a range of benefits to the developers, but the most important among them are:

  1. Type safety: Helps prevent errors and makes coding more efficient. 
  2. Code Intelligence and Refactoring: TypeScript provides superior code intelligence and refactoring capabilities. 

However, adding TypeScript to a React project also has its disadvantages. For instance, it requires more initial setup time and can slow down the development process due to the steep learning curve. 

Regardless of the tradeoffs, many developers believe that the benefits of using TypeScript in React projects outweigh the costs. And that's why learning how to use TypeScript with React can be a valuable skill for any developer.

Setting Up a React Project with TypeScript

TypeScript is developed by Microsoft that offers strict type-binding capabilities and can be compiled down to JavaScript, making it a great choice for large-scale projects. React, a popular JavaScript library for building user interfaces, can be used with TypeScript to provide additional type safety. 

To set up a new React project with TypeScript we can use the “create-react-app” tool or one can convert an existing project from JavaScript to TypeScript. And for state management and routing, frameworks like Redux can be easily integrated into React apps built with TypeScript.

Additionally, custom hooks can also be created using TypeScript with “create-react-app”. With the benefits of type safety and scalability, TypeScript in combination with React offers a powerful toolset for developing complex web apps

TypeScript Installation

To install TypeScript, you need to have Node.js and npm (Node Package Manager) installed on your system. Once you have Node.js and npm installed, you can install TypeScript by running the following command:

a. Installation using npm

//Install TypeScript globally

npm install -g typescript

//for Mac

sudo npm install -g typescript

//Verify TypeScript version installed

tsc -v

b. Installation using yarn

//Install TypeScript with yarn

yarn add --dev typescript

//Verify TypeScript version installed

yarn tsc -v

Now you can create TypeScript files, compile them to JavaScript, and run them in your environment of choice.

Configuring TypeScript for a React Project

To configure TypeScript for a React project, you can follow these steps:

1. Install the necessary React typings as a development dependency using either npm or yarn:

npm install --save-dev typescript @types/react @types/react-dom

// Or, using Yarn:

yarn add --dev typescript @types/react @types/react-dom

2. Create a tsconfig.json file in the root of your project with the following contents:

  "compilerOptions": {
    "target": "es5",
    "module": "esnext",
    "jsx": "react",
    "strict": true,
    "esModuleInterop": true

The “jsx” property is set to react to enable JSX syntax support, while other compiler options are set to enable strict type-checking and interoperability with CommonJS modules.

3. Rename your .js files to .tsx files so that TypeScript knows to parse them as TypeScript files that contain JSX syntax.
4. Start or restart your development server, and TypeScript should automatically compile your TypeScript code into JavaScript.

Note: If you're using Create React App (CRA), TypeScript support is built-in and you don't need to configure TypeScript manually. You can simply create a new app with the “ --template typescript flag”, like so:

npx create-react-app my-app --template typescript

// Or, using Yarn:

yarn create react-app my-app --template typescript

This will create a new React app with TypeScript support out-of-the-box.

Creating basic React TypeScript components

Creating basic React components with TypeScript involves defining the component's props, state, and rendering logic. Here are the basic steps:

prerequisites: Make sure you have both React and TypeScript installed in your project.

1. Define the Props and State interfaces:

Props and State are the two main ways to pass data between components. To define them, create an interface for each:

interface Props {
  title: string;
  description?: string;

interface State {
  count: number;

In this example, the Props interface specifies that the component requires a “title” prop, which is a string, and an optional “description” prop, which is also a string. The State interface specifies that the component has a single “count” property, which is a number.

2.Create the component:

Create a new .tsx file and import React and the required interfaces. Then create a new React component and define its props, state, and rendering logic:

import React, { Component } from "react";

interface Props {
  title: string;
  description?: string;

interface State {
  count: number;

export class MyComponent extends Component<Props, State> {
  constructor(props: Props) {

    this.state = {
      count: 0,

  render() {
    const { title, description } = this.props;
    const { count } = this.state;

    return (
        {description && <p>{description}</p>}
        <p>Count: {count}</p>

In this example, we define a class-based component called “MyComponent” that extends the “Component” class from React. We define the props and state types using the Props and State interfaces we defined earlier.

In the constructor, we set the initial state of the component. In the “render” method, we access the “title” and “description” props and the “count” state variable to render the component's UI.

3.Use the component:

To use the component in other parts of your application, import it and pass the required props:

import React from "react";
import { MyComponent } from "./MyComponent";

function App() {
  return (
      <MyComponent title="Hello World" />

In this example, we import the “MyComponent” component and use it in the “App” component by passing the required “title” prop.

Note that the “description” prop is optional, so we don't need to pass it if we don't want to.

Type Safety in React with TypeScript

Type Safety in React TypeScript refers to the ability to catch errors and bugs at compile time by checking that the types of variables, props, and states are correct. TypeScript introduces strict type binding for React projects. Its strict mode enforces type constraints, catches mismatch mistakes early in the development process, and improves security. 

In React, TypeScript can be used to define the types of props and states for components, as well as for event handlers and other functions. This helps ensure that components are used correctly and reduces the risk of errors caused by passing incorrect types of data to components or functions.

For example, let's say we have a component that expects a prop called “name” of “type” string. With TypeScript, we can define the type of this prop in the component's interface like this:

interface Props {
  name: string;

Now, if we try to pass a number or any other type of value to the name prop, TypeScript will give us a compile-time error, alerting us to the problem. This can help catch errors early in the development process before they cause problems in production.

TypeScript can also be used to define the return type of functions, which can help ensure that the functions are used correctly and avoid errors caused by returning the wrong type of value.

Type Safe your React components- Avoid common mistakes with Type Safety

Maintaining type safety in a React TypeScript project is important to ensure code quality and avoid bugs. Here are some common mistakes to avoid:

1. Not defining the types of props and states:

One of the main benefits of using TypeScript in React is the ability to define the types of props and states. Failing to do so can lead to bugs and errors, and defeats the purpose of using TypeScript. Always define the types of props and states to ensure type safety. Also, use interfaces or types to properly extend the component props.

2. Ignoring command injection and HTML injection attacks:

Never ignore potential attacks on your app. To prevent command injection and HTML injection attacks avoid building dynamic code with suspicious user input and use execFile instead of exec. 

3. Using any or unknown types:

While TypeScript allows for dynamic typing through any and unknown types, using them too liberally can defeat the purpose of using TypeScript for type safety. Always try to use more specific types wherever possible.

4. Ignoring TypeScript errors:

TypeScript is designed to catch errors at compile time, so ignoring TypeScript errors can lead to bugs and errors in production. Always fix TypeScript errors as soon as they appear.

5. Not updating types after changes:

If you make changes to a component's props or state, be sure to update the types accordingly. Failing to do so can lead to type errors and bugs.

6. Using type assertions excessively:

While type assertions can be useful for certain situations, using them excessively can lead to errors and defeat the purpose of using TypeScript for type safety. Use type assertions sparingly and only when necessary.

7. Not using generic types:

Using generic types can make code more reusable and easier to maintain. Failing to use generic types can lead to duplicated code and reduced maintainability.

Overall, maintaining type safety in a React TypeScript project requires attention to detail and a commitment to using TypeScript correctly. 

Benefits of type safety in React

When using TypeScript with React, there are several key benefits of maintaining type safety, including

  1. Catch errors early: Type safety ensures that you catch errors early in the development process, rather than at runtime. 
  2. Improv code readability: TypeScript's strong typing can improve the readability of your code by making it clearer what types of data are being passed around and what each component is expecting.
  3. Better collaboration: TypeScript can make it easier for developers to collaborate on projects by making the code more readable and by providing better documentation through type annotations.
  4. Enhanced tooling: Because TypeScript provides static analysis, it enables better tooling such as code completion and refactoring, which can help speed up development time and improve code quality.
  5. Declarative view:  TypeScript allows for more declarative views, making code more predictable and easier to debug. 
  6. Encapsulated components: React's component-based structure allows for building encapsulated components that manage their state and compose them to create complex UIs.
  7. More maintainable code: By catching errors early and making the code more readable, TypeScript can make your code more maintainable over time. 

Expedite your React TypeScript app development with DhiWise React Builder

In the blog we have seen how TypeScript’s Type Safety empowers you to build strong and scalable React applications by easily identifying errors during compilation. 

Also, With TypeScript implementation in your React projects, you can eliminate common mistakes and steer clear of performance issues. This enhances your development speed, improves code quality, and guarantees type safety.

Well, this is all about  Type safety in React TypeScript, but what if I tell you about the platform that accelerates the React TypeScript app development while ensuring code quality, customization flexibility, and scalability? 

Introducing DhiWise React Builder which now supports both TypeScript and JavaScript and also provides you with a range of features to speed up React app development. 

The React builder eliminates most of the repetitive tasks in app development such as design to code conversion, API integration, and management. On top of that, it lets you build a responsive UI that goes well with all platforms. 

Sign up today to explore more about DhiWise and build your next React TypeScript app with DhiWise React Builder.