A Complete Guide: How To Use Typescript With React

TypeScript with React
A Complete Guide: How To Use Typescript With React

React and TypeScript is 2 excellent technologies made to use by several developers nowadays. Identifying how to do something can be challenging, and sometimes it’s difficult to find a decent answer. However, you don’t have to worry about it as we have come up with the best practices together with examples to illustrate any issues you may have.

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 basically create our UIs using a JavaScript-typed version.

The purpose of using them together 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.

TypeScript with React: The Purpose

TypeScript is a JavaScript superset, so every JavaScript functionality can also be seen in TypeScript. However, TypeScript pushes JavaScript to go one step further by introducing a strong type system that allows code refactoring, navigation, type-checking, and more.

Typescript with React
React

This strong statically typed language is a paradise for React developers from all around the world. In reality, many of the React developers who implement TypeScript claim they can’t possibly imagine what their work is going to look like without it.

Benefits of Using TypeScript with React

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

Also Read | Learning Guide | TypeScript VS JavaScript
  1. Code Suggestions: Typescript provides suggestions and choices as you type. This allows you to save a lot of time, making it simpler for a new developer to use the source code. These code suggestions avoid the wastage of time, facilitate team coordination, and render the codebase more reliable.
  2. Readability and Validation: Because Typescript is a statically typed program, you are allowed to add types to variables, functions, and properties, making the code much simpler to understand. Typescript is often used to remove the PropTypes of React, the reason why React development becomes super easy.
  3. Identify bugs faster and IntelliSense: Among the most popular features of Typescript is its potential to identify bugs as early as possible. Typescript demonstrates the bugs before you really run the code, allowing you to save time to fix or rectify them.
  4. Effective code maintenance and refactoring: As the React app’s codebase expands, it may become too tough to interpret, share, or manage. Trying to navigate these codebases can be cumbersome, and refactoring the code is dangerous. Typescript also lets you refactor code to avoid typos, making it much easier to manage and upgrade without modifying any of its behaviours.
  5. Enhances the use of JavaScript: Typescript blends entirely with JavaScript and utilizes the latest functionality available to the JavaScript developer. React projects developed with Typescript compile to a JavaScript version running on any browser.

When should you be using TypeScript?

If you’re working on a project that you’re planning to run for a long time, you can use TypeScript from the first day. One of the better use cases may be that if you are making a library, you can write it in TypeScript, which will allow other programmers who use your library to anticipate inputs and assist with an error on the move.

TypeScript
TypeScript

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.

Also Read | Beginner’s Guide To Python

Go to the website to find out about the configuration options available.

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.

Also Read | Top 10 IDEs To Create Windows Apps
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 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 parts of development (yet the most dreaded one) is the configuration. Luckily, the react/typescript package generates the most basic tsconfig.json file for us, which, as the name suggests, is the configuration file for the typescript compiler. However, it is advised 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 reacting is reusable flexible components. These components make use of certain props necessary for behaving in accordance with certain conditions.

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

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 >
}

In A Nutshell…

The right approach to using React and TypeScript together 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 also learn! Next, you’re going to want to learn:

  • Creation of strongly-typed class components
  • React component props
  • Creation of a React TS project from scratch
  • Use of Babel and Webpack
  • Addition of npm scripts and more

If you want to hire a React Developer to work on your important projects, we have got your back. Codersera gives you the opportunity to hire the top 1% of developers. So, what are you waiting for?

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 can be used to build JavaScript applications for both client-side and server-side implementation. There are many methods available for transcompilation. You may either use the default TypeScript Checker or use the Babel compiler to convert TypeScript to JavaScript.

Typescript is essentially just stricter than Javascript. If you are well equipped with statically typed languages, then we would suggest working around Typescript. You’re going to have a little more syntax to master, but it’s going to be more comfortable and the compiler can hopefully deter you from doing anything incorrectly.

FAQ

Q1. Will TypeScript replace Javascript?

Ans- No, not in the short term. Given TypeScript is a typed superset of JavaScript, most developers will probably need to be comfortable working with JavaScript even if they are principally TypeScript developers.

Q2. What is the future of TypeScript?

Ans- TypeScript was used by 78% of the 2020 State of JS respondents, with 93% saying they would use it again. TypeScript continues to grow in popularity. It was voted the second most-loved programming language in the Stack Overflow 2020 Developer survey.