Typescript with React

How to use Typescript With React?

Abstract
This article is targeted towards those users who want to know about TypeScript and its compatibility with React. Here, we mainly focus on TypeScript. We will discuss the following point.

  • What is TypeScript?
  • How this is different from JavaScript?
  • Why should we use this in our projects?
  • Why TypeScript is developed while we have JavaScript?

So, there are many questions around it also but believe me once you know about it, you want to use it in your next project.

Introduction

TypeScript is nothing but the superset of JavaScript created by Microsoft Developers. TypeScript compiler compiles its code into plain JavaScript code (.js).

TypeScript is getting popular nowadays. We can also call this Typed JavaScript.
JavaScript + Types = TypeScript.
TypeScript is a statically typed language which means it supports the type checking at compile-time, unlike JavaScript which is a dynamically typed language.

What we meant by statically typed and dynamically typed language?

Statically Typed Language: This type of language does the type checking at compile time. This results in catching errors at compile-time and makes code less erroneous at runtime, apart from applying exceptions handlers.

Dynamically Typed Language: This type of language does the type checking at run time like JavaScript, PHP, etc.

Moreover, we can run TypeScript code on Node.js or any browser which supports ES 3 or newer versions.
TypeScript supports the concept of Object-Oriented Programming. TypeScript supports the concept like classes, interfaces, inheritance, etc.

Basic Concepts of TypeScript

Let’s Learn about the basics of TypeScript and how can we use it.
Declare and Initialization of variables
We can Declare and initialize the variables as an example given below:
var [ Identifier] : [Type-Annotation] = value;
var name: string = “Name”;
// Declare a name variable of string type initialize with a value name.

var [Identifier]: [Type-Annotation];
var name:String;
// Declare a variable of name have undefined value.

var [Identifier] = value;
var name = “name”

// Declare a variable without any type annotation and initialize with value name which also became the type of variable.
var name;
// Declare a variable without type annotation and value.

We can also change the variable type which is known as Type Assertion. For Ex.

var str = “1”;
var str2:number = str;
console.log(str === str2);
Output: false; //Output

var nums : number [ ] = [1,2,3,3];

This is how we can declare and initialize the array.

We can also create tuple if we want to store different types of values but it follows sequences strictly.

var num : [“string”, “number”] = [“Name” , 5]
var num : [“string” , “number”] = [5 , “Name”] //Error

TypeScript is a statically typed language but it does not mean that it cannot support the dynamically typed language. As per the above example in TypeScript, we can declare the variable without type and in this case TypeScript assign type of the value to that variable.

But after initializing variable without type, if we assign it another type of value then TypeScript Compiler throws an error.

● Declaring a function in TypeScript

function name(paramter1[:type], parameter2[:type], parameter3[:type]): [type]{}

In TypeScript, there is term Optional parameter. Which can be used when arguments are not compulsory for the function’s execution.

function emp(id:number, name:string, mail?:string): {}

In the above example mail is not a compulsory field. If we do not pass the mail field then it’s value treated as undefined. We can call the above functions like this.

emp(1, ‘name’);
emp(2, ‘name’, ‘name@gmail.com’);

● Anonymous function
In this, we store the function reference in variable.
var res = function( [arguments] ) { … }

For Example:

var multiply = function(a:number,b:number) {
return a*b;
};
console.log(res(4 ,2))

// outputs 8

Lambda Function
Lambda function is the functions that are not bound to any identifier.

( [parameter1, parmeter2, …parameter n] ) => statement;
For Example:
var add = (x:number)=>10 + x
console.log(add(50))
//outputs 60

We can combine two or more data types by using the union operator (|).
For Ex.

function getList(list: string|string[]) {
var val: sting|number;
val = 1;
val = “name”;
return list;
};
console.log(res([‘a’, ‘b’]))
//outputs 8

Interface

Like any object-oriented programming language, we can define the interfaces in TypeScript. The interface is nothing but the road map or the blueprint of the classes. In another way, it defines that the class can contain these functions or objects.

interface Person{
name: String,
printName: ()=>string
}
var human: Person{ name: “name”;
printName: (): string => {return “name”} }

We can also define an interface like below example.

interface namelist {
[index:number]:string
}

var list: namelist = [“John”,”Bran”] //Successfully Execute
var list: namelist = [“John”,1,”Bran”] //Error. 1 is not type string

It defines an array of which index is in numeric and value should be a string. Also, we can do just opposite take string as an index and number as a value as given below in example:

interface ages {
[index:string]:number
}

var agelist:ages;
agelist[“John”] = 5

Classes

What is a class? As we all knew that in class we can encapsulate all the data and functions from the object. TypeScript support OOPS features like interfaces and classes as you can see in the above points. It gets this feature from ES6.

class Human{
//field
name:string;

//constructor
constructor(name:string) {
this.name = name
}

//function
getName():void {
console.log(“Name is : “+this.name) } }

As you can see in the example above, it’s just like any other Object-Oriented-Programming languages.
We can declare variables, constructor methods just like JAVA.

We can create an object of that class to access its fields and method.

var obj = new Human(“Ajay”)

//access the field
console.log(“Human : “+obj.name)

//access the function
obj.getName()

● Inheritance

Inheritance, Anyone who is from an object-oriented background heard about it. Inheritance is a way to inherit the property in terms of operations/functions of the parent class.

To inherit the property of one class to another or one interface to another interface we use the keyword “extends”.
For inheriting the property on an interface into class we use the “implements” keyword.

class Engine{
engine:string
constructor(a:string) {
this.engine = a
}
}
class Bike extends Engine{
start():void {
console.log(this.engine)
}
}
var obj = new Bike(“start”);
obj.start()
interface Name { Name: string }
interface Address{ Street: string }
interface Human extends Name, Address{ }

Var human: Child = { Name: “ajay”, Street: “noida”}
console.log(“value 1: “+this.Name+” value 2: “+this.Street)

We can also use the method overriding (means override the parent class method).

NameSpaces

It is the inbuilt functionality of TypeScript. A namespace is used to group the related code logically. Unlike the JavaScript files when we declare the variable, it goes into global scope while using var and if multiple files used it then it may be possible that it overwrites the same variable, which can cause to “global namespace pollution problem” in JS.

export interface ISomeInterfaceName { }
export class SomeClassName { }
}

How to use TypeScript with React?

If you are using node 8 or its upper version, you can directly install typescript by using the following command.

npx create-react-app app_name –typescript

There are many noticeable changes from JavaScript related CRA.

tsconfig.json file configuring the compiler options for Typescript.
.jsx(JavaScript) files are now .tsx (TypeScript) files. The Typescript compiler will take all .tsx files at compile time.
package.json contains all the dependencies for @types packages, including support for React, React-DOM, etc..

Running npm start will compile and run your app.

There is another way to setup TypeScript with React from scratch.

You have to create the following files.

fileStructureForTypeScript

1. Go to the My-App folder and run npm init. It will create a package.json file.
2. Install React and React-DOM by command npm install react react-dom.
3. The next packages are only for development dependencies, the code will be compiled to es5. So, we do not need typescript for the packages or webpack as a dependency in our production code.

awesome-typescript-loader will transpile your Typescript code into es5 so that your browser understands what to do with your code. There are many configurations which we can use in webpack.

npm i -D awesome-typescript-loader @types/react @types/react-dom html-webpack-plugin @types/html-webpack-plugin typescript webpack webpack-cli @types/webpack webpack-dev-server ts-node

4. webpack.dev.ts, For the dev configuration, we have to import a webpack and a plugin known as Html-webpack-plugin. After the imports, we will create an instance in the Html-web-plugin object so that we will use it as a plugin in the webpack configuration. It will be used to fire up the index.html page when we start the development server.

import * as webpack from “webpack”;
import * as HtmlWebPackPlugin from “html-webpack-plugin”;

const htmlPlugin = new HtmlWebPackPlugin({
template: “./index.html”
});

const config: webpack.Configuration = {
mode: “development”,
entry: “./index.tsx”,
resolve: {
extensions: [“.ts”, “.tsx”, “.js”, “.json”]
},
module: {rules: [
{ test: /\.tsx?$/, loader: “awesome-typescript-loader” }]},
plugins: [htmlPlugin]
};
export default config;

5. Webpack.prod.ts, when we run it makes a new folder, which contains the transpile code.

import * as path from “path”;
import * as webpack from “webpack”;
import * as HtmlWebPackPlugin from “html-webpack-plugin”;
const htmlPlugin = new HtmlWebPackPlugin({
template: “./index.html”,
filename: “./index.html”});
const config: webpack.Configuration = {
mode: “production”, entry: “./index.tsx”,
output: {path: path.resolve(__dirname, “dist”), filename:”bundle.js”},
resolve: {extensions: [“.ts”, “.tsx”, “.js”, “.json”]},
module: {rules: [{ test: /\.tsx?$/, loader: “awesome-typescript-loader” }]},
plugins: [htmlPlugin]
};

export default config;

6. In package.json we have to add the following lines. These lines add a new script, which used to run the development or production server.

“scripts”: {“dev”: “webpack-dev-server –open –config webpack.dev.ts”,
“build”: “webpack –mode production –config webpack.prod.ts”
},

7. We have to set up the compiler options for the typescript configurations, we do that in order to be able to run the code, in a way we want it to work.

{
“compilerOptions”: {
“outDir”: “./dist/”,
“noImplicitAny”: true,
“target”: “es5”,
“lib”: [“es5”, “es6”, “dom”],
“jsx”: “react”,
“allowJs”: true,
“moduleResolution”: “node”
}
}

8. Index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>TypeScript with React</title>
</head>
<body>
<section id="root"> </section>
</body> </html>

9. App.tsx


import * as React from "react";
export default class APP{
render(){ return <head>Hello</head>;}
}

10. Index.tsx


import * as React from "react";
import * as ReactDOM from "react-dom";
import App from "./src/App";
const Index = () => {
return <App/>;
};
ReactDOM.render(<Index/>, document.getElementById("root"));

11. Use npm run dev, this syntax will fire up your development server and a browser tab will open with the port 8080. And use npm run build to run your code in production mode.

Features of TypeScript

● TypeScript code cannot be understandable by the browsers. That’s why if we write the code in TypeScript it will be compiled and the code gets converted into JavaScript. This process is known as “Trans-piled”.
● In TypeScript, we can use the existing JS code, popular JS libraries and also can be called from other JavaScript code.
● We can run the TypeScript code on any browser, devices or in any operating system.
● All the code written in JavaScript can be changed into TypeScript just by changing the extension (from .js to .ts)

Difference between TypeScript and JavaScript:

● JavaScript is a scripting language whereas TypesScript is known as Object-Oriented Programming(OOPS) language.
● TypeScript is Statically typed while JavaScript is Dynamically Typed. TypeScript also supports Dynamic Typing while JavaScript does not support Static typing.
● TypeScript provides support for modules whereas JavaScript does not support modules.
● TypeScript has the concept of Interface but JavaScript does not have.

Advantages of using TypeScript over JavaScript

● In TypeScript, we get the compilation error at development time as it’s a statically typed language. Due to this, we have fewer chances to get those silly errors at run time like the variable is undefined whereas JavaScript is Interpreted language at providing the errors at run time.
● TypeScript has a feature that is strongly-typed or supports static typing.
● TypeScript is just a JavaScript with some additional features i.e. ES6 features. TypeScript can compile the .ts files into ES3, ES4, and ES5 also.

Disadvantages of using TypeScript against JavaScript

● Generally, It takes time to compile the code.
● It does not support abstract classes.

About Author:
Author Saurabh Singh is a Full stack developer currently working with QSS Technosoft. He has completed his bachelor’s degree in Computer Science and Engineering. He is always keen to explore new technologies.

About QSS:

QSS Technosoft is a top-notch React Development Company based in India & USA. The company offers the best React development services for building highly interactive cross-platform mobile apps at a lightning-fast speed.

Focusing on your success by creating most user-friendly web & mobile apps, the company feels proud mentioning its large base of happy clients from across the globe. Contact us for your React development requirements filling the form below. 

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *

Hire certified

Developers

  • Avg. 6+ Years of Experience.
  • Dedicated Resource on Demand.
  • NDA Protected Terms.
  • Start/Interview within 24 Hours.
  • Flexible Engagement Models.
  • Best code practices.
Start Now!
E-Book

eBook

6 Most Important Factors for a Successful Mobile App!

Every precaution that you take in the development process will help you to be effective in building products that will help you grow and reach your goals. Consider these 6 factors before heading for mobile app development.

Subscribe to our newsletter and stay updated

Loading