Introduction to React and TypeScript: How to Create React App Using Typescript

React and TypeScript are two powerhouse technologies that many developers are diving into. Navigating the process of creating a React app with TypeScript can be a bit complex, and finding solid advice isn’t always straightforward. However, there’s no need to worry. We’ve gathered some of the best practices and put together examples to smooth out any issues you might face when you create a react app with typescript.

create react app using typescript

Before we start, let’s review how React and TypeScript function around each other. React is a “JavaScript library for creating user interfaces” while TypeScript is a “typed JavaScript superset that compiles a plain JavaScript.” By making use of them jointly, we create our UIs using a JavaScript-typed version.

Learn more: Comparison of TypeScript vs JavaScript

The purpose of creating a react app with Typescript will be to get the advantages of a statically typed language (TypeScript) for your UI. This ensures more security and fewer errors on the front end.

Why use Typescript with React?

TypeScript enhances JavaScript by being its superset, meaning it encompasses all JavaScript features and capabilities. Yet, it takes JavaScript to the next level with the addition of a robust typing system. This system facilitates code refactoring, navigation, and type checking, among other features, elevating TypeScript beyond basic JavaScript functionality.

For React developers globally, TypeScript is often seen as an essential tool. The introduction of TypeScript has significantly impacted many React developers, who now find it difficult to envision their workflow and project development without the benefits it provides.

Let us narrow down the advantages of Typescript and demonstrate how it makes the frontend React development a piece of cake.

Strong Typing

Unlike JavaScript, TypeScript enforces type-checking at compile time. This means that developers who need to create React apps using Typescript can catch errors early in the development process, reducing runtime errors and ensuring code quality. For React developers, this translates to a more reliable codebase, as props and state can be typed, making component contracts explicit and reducing the likelihood of passing incorrect data types.

Read More:   7 Principles Of Web Design - update 2022

Enhanced Code Quality and Maintainability

TypeScript’s type system encourages better coding practices, leading to cleaner, more maintainable code. It facilitates code refactoring and navigation, which is particularly beneficial in large-scale React projects where components can be highly nested and interdependent. The ability to define interfaces and types makes the codebase more readable and easier to understand, which is crucial for onboarding new developers and maintaining the project long-term.

Improved Development Experience

With TypeScript, developers get access to advanced features like code autocompletion and IntelliSense in their IDEs. This not only speeds up the development process by reducing the need to remember the exact API calls but also minimizes typos and other common mistakes. For React development, this means quicker component creation and modification, with immediate feedback on props and state management issues.

Ecosystem Compatibility and Future-Proofing

TypeScript is designed to be compatible with existing JavaScript libraries and frameworks, making it easy to integrate into existing React projects. Moreover, as the JavaScript ecosystem evolves, TypeScript is quickly updated to include new features, ensuring that React projects using TypeScript stay up-to-date with the latest developments in web standards.

Enhanced Collaboration

TypeScript’s explicit type definitions make it easier for teams to collaborate on React projects. Developers can understand each other’s code more easily, making peer reviews more effective and reducing the risk of misunderstandings and bugs being introduced into the codebase.

When should you be using TypeScript?

create react app using typescript

If you’re kicking off a project you intend to maintain over the long haul, consider using TypeScript right from the start. A great scenario for this might be if you’re developing a library. Crafting it in TypeScript helps other developers use your library to predict inputs and manage errors more effectively as they work.

Configuration of TypeScript

TypeScript offers the possibility to configure a compiler. You could configure however strict you want TypeScript to be, prefer error types, define the target version of the ECMAScript, allow the source map, etc.

Both of these configurations are performed in the tsconfig.json file located at the root of the project. If a blank object is transferred, TypeScript will use the default configurations.

Is Typescript worth it?

Absolutely. TypeScript has been on the scene for a while, and it’s only gotten better with age. Regular updates mean it’s packed with new features, better performance, and smoother functionality. More developers and companies are choosing TypeScript over JavaScript, thanks to its added safety and improved tooling. It’s not just about catching errors early anymore; it’s about making coding cleaner, more predictable, and easier to manage in the long run

Read More:   Single-Page vs Multi-Page Website For A New Startup Business

How To Setup TypeScript in React App?

1. Making a new React app using the create-react-app v2.1 or higher

create-react-app 2.1 has now been integrated into the typescript. If you are building a new project using CRA, use—typescript as a standard and the new project will be set up using typescript.

npx create-react-app codersera-react-tsx --typescript

2. Add TypeScript to the current create-react-app project

When you wish to add TypeScript to a current application, then installing TypeScript and all the necessary types will be important.

npm install --save typescript @types/node @types/react @types/react-dom @types/jest

You may have to rename the files to .ts or .tsx and then begin the server. This will create the tsconfig.json file automatically and you will be ready to write React in TypeScript.

3. Add TypeScript to React when you do not use the create-react-app

If you don’t use the create-react app, the next most popular way to set up React is to use the webpack. Let’s find out everything you need to change in the configuration of your webpack to get TypeScript.

1. Installation of required packages
npm install --save-dev typescript awesome-typescript-loader

Below are the packages you need to install:

  1. Typescript: This package is used to compile the TypeScript code into the JavaScript code.
  2. awesome-typescript-loader: As a webpack, it just recognizes simple CSS, javascript, and HTML. This is a webpack loader that allows users to communicate the typescript webpack to compile the TypeScript code into the JavaScript code. You may configure a compilation, please check the official documentation for this loader.
2. Make the webpack configuration updation

Once all the packages are installed, you want to tell webpack the file format of TypeScript, i.e. extension files .ts and.tsx. In addition to the file format, we also need to tell the webpack which loader can handle this file format. For example, to convert .scss files to CSS, a webpack requires a sass-loader package.

3. Add the TypeScript configuration file

Finally, you may want to add the config file to the root of the project. You can edit this file and get the TypeScript according to your needs and requirements.

Using TypeScript with React

Begin by developing a new React project and integrating TypeScript. Execute the following commands to start the project:

npx create-react-app codersera-react-tsx --typescript

Remember the configuration advantage of typescript just mentioned earlier in this blog? Good time to implement it.

So one of the most important part of development (yet most dreaded one) is the configuration. Luckily, the react/typescript package generates the most basic tsconfig.json file for us, which, as name suggests, is the configuration file for the typescript compiler. However, it is adviced to modify that tsconfig.json file to match the one below to get started:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true, /* allows javaScript files to be compiled */    "skipLibCheck": true, /* skip type checking of all declaration files */    "esModuleInterop": true, /* disables namespace imports (import * as fs from "fs") and enables CJS/AMD/UMD style imports (import fs from "fs") */    "allowSyntheticDefaultImports": true, /* allows default imports from modules with no default export */    "strict": true, /* enables all strict type checking options */    "module": "esnext", /* specifies module code generation */    "moduleResolution": "node", /* resolves modules using Node engine */    "isolatedModules": true, /* unconditionally emits imports for unresolved files */    "resolveJsonModule": true, /* includes modules imported with .json extension */    "noEmit": true, /* Not to compile code, only performs type checking */    "jsx": "react", /* Support JSX in .tsx files (This one comes in handy sometimes) */    "sourceMap": true, /* generates corrresponding .map file */    "declaration": true, /* generate corresponding .d.ts file */    "noUnusedLocals": true, /* reports errors on unused locals (suggested for clean code writing) */    "noUnusedParameters": true, /* report errors on unused parameters (again, suggested for clean code writing) */  },
  "include": [
    "src/**/*" // *** The files TypeScript should type check ***
  ],
  "exclude": ["node_modules", "build"] // *** The files to not type check ***
}

Now, one of the core concepts of react is reusable flexible components. These components make use of certain props necessary for behaving in accordance to certain conditions.

Read More:   Comparison of TypeScript vs JavaScript

In typescript, props can be defined by either an interface or type as:

import React from 'react'

interface Props {
employeeName: string;
employeeCode: number;
}

type OtherProps = {
employeeName: string;
employeeCode: number;
}

/* Notice here the props are destructed in the function arguments by referencing its definition above */
function EmployeeBadge({ employeeName, employeeCode }: Props): React.ReactNode {
return <p>I am an employee!<p>
}

 

Advantages of using typescript to create React app

One of the good advantages of TypeScript is that when composing React components with JavaScript vanilla, we used linters and prop-types to maintain code quality and detect errors. The key issue with PropTypes is that it operates during runtime.

TypeScript is versatile enough to develop JavaScript apps for both client-side and server-side execution. There’s a variety of ways to transcompile, allowing you to either stick with the native TypeScript compiler or opt for the Babel compiler to turn TypeScript into JavaScript. Essentially, TypeScript enforces stricter rules compared to JavaScript. If you’re familiar with statically typed languages, diving into TypeScript is a good move. Although there’s a bit more syntax to get your head around, it leads to a smoother development experience, and the compiler is there to help prevent mistakes.

Conclusion on how to create react app using typescript

The right approach to creating a React App with Typescript is to keep learning step by step, and the benefits will start paying tremendously in the coming years. Now that you’ve got a basic overview of what Typescript is and what it can do for your React projects, you will be better able to work on your projects. There’s a lot more than Typescript could do for React and a lot to learn!

If you want to hire a React Developer to work on your important projects, we have got your back. InApps allows you to hire the top 1% of developers at reasonable prices. So, let’s get in touch!

 

5/5 - (1 vote)
I am a dynamic Tech Explorer and Writer for InApps Technology. With a background in software engineering and a knack for writing, my content brings a fresh and insightful perspective to the tech scene. I love making their content not just informative but also incredibly engaging for both tech novices and aficionados. Join me on a journey through the ever-evolving digital landscape, where I decode complex concepts into captivating stories.

Let’s create the next big thing together!

Coming together is a beginning. Keeping together is progress. Working together is success.

Let’s talk

Get a custom Proposal

Please fill in your information and your need to get a suitable solution.

    You need to enter your email to download

      [cf7sr-simple-recaptcha]

      Success. Downloading...