Promptless AI is here soon - Production-ready contextual code. Don't just take our word for it. Know more
Know More

A Comprehensive Overview : How to Create React App Typescript?

No items found.

Rakesh Purohit

ReactJS Developer Advocate
August 8, 2023

Rakesh Purohit

August 8, 2023

A Comprehensive Overview : How to Create React App Typescript?

TypeScript, a statically typed superset of JavaScript, has been gaining popularity among developers for its ability to catch errors at compile-time, rather than runtime.

This feature, along with robust tooling and better code completion, makes TypeScript an attractive option for many developers, especially those working on large-scale projects.

The Synergy of TypeScript and React

React, a popular JavaScript library for building user interfaces, pairs exceptionally well with TypeScript. The strong typing of TypeScript allows for better autocompletion, easier navigation of your codebase, and a more robust development experience overall.

Setting up a new Create React App TypeScript

Before we can create React app TypeScript, we need to ensure that Node.js and npm (Node Package Manager) are installed on our system.

Node.js is a JavaScript runtime that allows us to run JavaScript code outside of a browser, while npm is a package manager for JavaScript, allowing us to install and manage project dependencies.

You can verify if Node.js and npm are installed by running the following commands in your terminal:

If these commands return versions, then Node.js and npm are installed. If not, you'll need to install them. You can download Node.js and npm from the official Node.js website.

Once Node.js and npm are installed, we can create a new React app with TypeScript. The Create React App project provides a TypeScript template that sets up a new project with TypeScript configuration and file structure.

To create a new React app with TypeScript, run the following command in your terminal:

This command creates a new React app with the name "my-app" using the TypeScript template. You can replace "my-app" with the name of your app.

After running the command, you'll have a new directory with the name of your app. Inside this directory, you'll find the initial project structure and files.

The src directory is where you'll write your React and TypeScript code. You'll notice that the file extensions for React components are .tsx instead of .js, indicating that these are TypeScript files.

The tsconfig.json file is the TypeScript configuration file. This file tells the TypeScript compiler how to transpile the TypeScript code. You'll notice that the jsx option is set to "react", which allows us to write JSX in our TypeScript files.

In the next sections, we'll dive deeper into how to write React code with TypeScript, how to add TypeScript to an existing React project, and more. Stay tuned!

Integrating TypeScript into an Existing React Project

If you have an existing React project and you want to start using TypeScript, the first step is to install TypeScript as a dev dependency. You can do this by running the following command in your project directory:

This command installs TypeScript and adds it to your package.json file under the devDependencies section.

The next step is to rename your .js or .jsx files to .tsx. This tells the TypeScript compiler to treat these files as TypeScript. You can do this manually, or if you have a lot of files, you can use a tool like rename to rename them all at once.

This command renames all .jsx files in the src directory and its subdirectories to .tsx.

After renaming your files, you need to add a tsconfig.json file to your project root. This file configures the TypeScript compiler. You can generate a default tsconfig.json file by running the following command:

This command generates a tsconfig.json file with default settings. You can modify these settings to suit your project needs.

After adding the tsconfig.json file, you might see TypeScript errors in your .tsx files. These errors occur because TypeScript is stricter than JavaScript and enforces types. You'll need to resolve these errors before you can run your project.

Resolving TypeScript errors usually involves adding types to your variables, functions, and components. We'll discuss how to do this in the following sections.

Building a Sample App with React and TypeScript

I recently stumbled upon a tool that has been a game-changer for my React and TypeScript development process. It's called WiseGPT, a promptless Generative AI specifically designed for React developers. It's like having a pair of extra hands that write code in your style, without any context limit. It's been incredibly helpful, especially when I'm working on complex components or dealing with tricky TypeScript types. But how does it know my coding style? And how does it manage to integrate so seamlessly with my existing workflow, even accepting Postman collections for API integration? It's almost like it's reading my mind, predicting what I need before I even ask. How does it do that? You must go to WiseGPT page to know.

Let's start building a simple app to understand how TypeScript works with React. We'll create a Todo app where users can add and delete tasks. First, let's create a Todo functional component:

In the above code, we define a Todo component that takes text and complete as props. The text is the task description, and complete is a boolean indicating whether the task is completed.

React hooks let us use state and other React features without writing a class. To add state to our Todo component, we can use the useState hook. Let's add a state variable for the task description:

In the above code, we define a state variable task and a function setTask to update it. We use the useState hook to initialize task with an empty string. We also define a handleInputChange function to update task when the input field changes.

In TypeScript, we can define types for event handlers to ensure we're using the correct event object.

For example, in the handleInputChange function above, we define the event parameter as React.ChangeEvent<HTMLInputElement>, which is the type for change events on input elements.

This gives us type-checking and autocompletion for the event object.

Advanced TypeScript Concepts in React

In TypeScript, a generic type is a type that is associated with another type. We often use generic types in React with props and state. For example, the React.FC type is a generic type that takes the props type as a parameter.

Let's look at an example of a generic type with the useState hook:

In the above code, Array<string> is a generic type that represents an array of strings. This tells TypeScript that todos is an array of strings.

In addition to interfaces, we can use type aliases to define prop types in React. A type alias is like an interface, but can represent more complex types and can be used in a broader range of situations.

Here's an example of a type alias for prop types:

In this example, Props is a type alias that we use to type the props of the Person component.

When using third-party libraries with TypeScript, we often need to install type definitions for those libraries. These type definitions provide TypeScript with the information it needs to understand the types used by the library.

For example, if we're using the lodash library, we can install its type definitions with the following command:

This command installs the type definitions for lodash and adds them to our devDependencies. Now we can use lodash in our TypeScript code with full type checking and autocompletion.

Debugging and Testing TypeScript in React

A. Setting up a development server

When working with TypeScript in a React project, it's essential to have a development server that supports hot module replacement and can transpile TypeScript to JavaScript on the fly.

Create React App provides such a server out of the box. You can start the development server by running the following command in your project directory:

This command starts the development server and opens your app in a web browser. The server watches for changes in your files and automatically refreshes the page whenever you save a file.

B. Using TypeScript compiler for debugging

The TypeScript compiler can be a powerful debugging tool. When you run the compiler, it checks your code for errors and shows you detailed error messages.

You can run the TypeScript compiler in watch mode, which means it will recheck your code whenever you save a file. To start the TypeScript compiler in watch mode, run the following command:

This command starts the TypeScript compiler in watch mode. Now, whenever you save a file, the compiler will check it for errors and show you any errors in the terminal.

C. Writing tests for TypeScript in React

Writing tests is an important part of software development, and TypeScript can make writing tests easier and more robust.

When you write tests in TypeScript, the compiler checks your test code for errors, just like it checks your app code. This can help catch errors in your tests and make your tests more reliable.

Here's an example of a test for a React component written in TypeScript:

In this example, we're using the @testing-library/react library to render the App component and check that it contains a text "learn react". The TypeScript compiler checks this test code for errors, just like it checks our app code.

Best Practices for Using TypeScript in React

A. Organizing project files

When working with TypeScript in a React project, it's important to keep your project files organized.

Keep related files together. For example, if you have a component and a corresponding CSS module, keep them in the same directory.

Use a consistent naming convention for your files. For example, you could use PascalCase for component files and camelCase for non-component files.

Keep your tsconfig.json file at the root of your project. This makes it easy to find and modify your TypeScript configuration.

B. Handling errors and exceptions

TypeScript can help catch errors at compile-time, but it can't catch all errors. Some errors can only occur at runtime, so it's important to handle these errors in your code.

Use try/catch blocks to handle runtime errors.

Use the nullish coalescing operator (??) and optional chaining (?.) to handle null and undefined values.

Use type guards to narrow down the type of a variable.

C. Code completion and other IDE features

One of the benefits of using TypeScript is the enhanced development experience it provides. Many IDEs, including Visual Studio Code, provide features like code completion, type checking, and refactoring for TypeScript.

Use code completion to explore the properties and methods available on an object.

Use the "Go to definition" feature to navigate to the definition of a variable or function.

Use the refactoring features to safely rename variables and functions, extract code into functions or variables, and more.

Real-world Applications of TypeScript in React

A. Building mobile applications with React and TypeScript

React Native is a popular framework for building mobile applications using React. TypeScript can be a great addition to a React Native project, providing the same benefits as in a web project. The setup process is similar to a web project, and the development experience is equally enjoyable.

B. Developing large-scale projects with TypeScript

TypeScript shines in large-scale projects. The static typing and tooling features of TypeScript can make it easier to navigate and understand a large codebase. Many large companies, including Microsoft, Airbnb, and Slack, use TypeScript in their projects.

C. Case studies of successful projects using TypeScript in React

There are many examples of successful projects that use TypeScript and React. One example is the Visual Studio Code editor, which is built with TypeScript and uses React for some of its UI. Another example is Airbnb's design system, which is built with TypeScript and React. These projects demonstrate the power and flexibility of TypeScript in real-world applications.

Resources and Further Learning

There are many online courses and tutorials that can help you learn TypeScript and React. I recommend React + TypeScript Cheatsheets on GitHub

Community forums and Q&A sites like Stack Overflow can be great places to get help and learn from other developers. The TypeScript section on Stack Overflow has many questions and answers about TypeScript. The DhiWise Discord community is another great place to connect with other React and TypeScript developers.

Remember, learning TypeScript and React is a journey. Take your time, practice regularly, and don't be afraid to ask for help. Happy coding!

Frequently asked questions

Frequently asked questions

No items found.