In Focus

React With TypeScript

This is a very good combination to develop client-side applications. The advantage of this combination is that React is one of the best frameworks in terms of performance. Similarly, TypeScript is having some better features as compared to JavaScript.

About TypeScript

Those very new to TypeScript, here are some basics of TypeScript. TypeScript is a strongly typed, object-oriented, compiled language. It is an open-source programming language developed and maintained by Microsoft. It is said to be a strict syntactical superset of JavaScript and adds optional static typing to the language. TypeScript is designed for development of large applications and transcompiles to JavaScript.

React With TypeScript 

In simple words, if we are writing code in TypeScript and the extension for saving code is .ts. Then, using transpiler (TypeScript Compiler) we are converting this to JavaScript and then only the execution is done. 

Basic Types
  • Boolean
    • g let isValid:boolean
  • Number
    • g let age:number
  • String
    • g let name:string
  • Array
    • g let days:string[]
  • Tuple
    • let x: [string, number];
  • Any
    • let customer: any;
Function
  1. addNumbers(num1:number, num2:number):number{  
  2.     return num1+num2;  
  3. }  
Class

  1. class Employee  {  
  2.             private firstName: string;  
  3.             private lastName: string;  
  4.             private email: string;  
  5.             private address: string;  
  6.   
  7.     Constructor(firstName:string, lastName:string, email:string, address:string){  
  8. This.firstName = firstName;  
  9.             This.lastName = lastName;  
  10.             This.address = address;  
  11. }  
  12. }  
Interfaces
  1. interface Vehicle {  
  2. color: string;  
  3. make: string;  
  4. }  
  5. class Car implements Vehicle {  
  6. color: string;  
  7. make: string;  
  8. constructor(color: string, make:string) {  
  9.     this.color = color;  
  10.     this.make = make;  
  11. }  
  12. }  
Generics

Generic class

  1. class GenericNumber<T> {  
  2.     zeroValue: T;  
  3.     add: (x: T, y: T) => T;  
  4. }  
  5.   
  6. let myGenericNumber = new GenericNumber<number>();  
  7. myGenericNumber.zeroValue = 0;  
  8. myGenericNumber.add = function(x, y) { return x + y; };  
  9.   
  10. Generic function  
  11. getData<T>(arg: T): T {  
  12.     return arg;  
  13. }  
  14. let countryName = getData<string>("india");  
  15. let countryCode = getData<number>(91);  

For more information, please visit here.

About ReactJS

React.js is a component-based UI development framework. React is useful not only for developing the web application but with it, we can develop native mobile apps as well. To understand more about web applications, please visit here and for the mobile native apps, go here.

React with TypeScript

First, we can set up the environment. The following two npm commands can easily build a sample application.

npm install -g create-react-app
npx create-react-app react-ts-app --scripts-version=react-scripts-ts A

Now, just go to the folder react-ts-app using the following command.

cd react-ts-app

After the installation is done, use any IDE to open the application. I am using Visual Studio Code as this is free and light-weight.

React With TypeScript 

Open app.tsx and modify.

  1. import * as React from 'react';  
  2. import './App.css';  
  3.   
  4. class App extends React.Component {  
  5.  public render() {  
  6.    return (  
  7.      <div className="App">  
  8.        <header className="App-header">  
  9.          <h1 className="App-title">React with typescript</h1>  
  10.        </header>  
  11.        <p className="App-intro">  
  12.          This React application developed using typescript    
  13.        </p>  
  14.      </div>  
  15.    );  
  16.  }  
  17. }  
  18.   
  19. export default App;  

Use the below command to run the application.

npm start or yarn start

React With TypeScript 

After successfully executing the basic application, now we can start exploring the folder structure and the way of execution.

  • JSON

    • contains script for application execution
    • dependencies
      1. {  
      2.  "name""react-ts-app",  
      3.  "version""0.1.0",  
      4.  "private"true,  
      5.  "dependencies": {  
      6.    "react""^16.6.3",  
      7.    "react-dom""^16.6.3",  
      8.    "react-scripts-ts""3.1.0"  
      9.  },  
      10.  "scripts": {  
      11.    "start""react-scripts-ts start",  
      12.    "build""react-scripts-ts build",  
      13.    "test""react-scripts-ts test --env=jsdom",  
      14.    "eject""react-scripts-ts eject"  
      15.  },  
      16.  "devDependencies": {  
      17.    "@types/jest""^23.3.10",  
      18.    "@types/node""^10.12.15",  
      19.    "@types/react""^16.7.17",  
      20.    "@types/react-dom""^16.0.11",  
      21.    "typescript""^3.2.2"  
      22.  }  
      23. }  
  • Public/index.html

    • It is the main html page. <div id="root"></div> is a div where whole React application gets integrated.

  • src/index.tsx

    • This file contains the code which is actually used to read the HTML div element and integrate with the React code.
      1. import * as React from 'react';  
      2. import * as ReactDOM from 'react-dom';  
      3. import App from './App';  
      4. import './index.css';  
      5. import registerServiceWorker from './registerServiceWorker';  
      6.   
      7. ReactDOM.render(  
      8.  <App />,  
      9.  document.getElementById('root') as HTMLElement  
      10. );  
      11. registerServiceWorker();  
  • src/app.tsx

    • The actual code of the first component written. So, if you want to start changing the application, this is the right place.
      1. import * as React from 'react';  
      2. import './App.css';  
      3.   
      4. class App extends React.Component {  
      5.  public handleClick = () => {  
      6.    this.setState({ clicked: true });  
      7.  }  
      8.   
      9.  public render() {  
      10.    return <div>  
      11.      <h1>welcome to react with typescript</h1>       
      12.    </div>;  
      13.  }  
      14. }  
      15.   
      16. export default App;  
  • src/index.css

    • We can add stylesheet for our application here only. There is only one difference between the HTML with CSS integration and TSX with CSS integration, that is, in HTML/CSS, we can write <div class=”sample”></div> and in CSS .sample{margin=12px;} this way. But in tsx/css, we can write <div className=”sample”></div> and in CSS .sample{margin=12px;}. Then only, our CSS reflects the changes.This is a React-specific change.
  • src/app.test.tsx

    • In this file, we can write unit tests related to the app components. Similarly, we can add a component and also, test a class for unit testing.
      1. import * as React from 'react';  
      2. import * as ReactDOM from 'react-dom';  
      3. import App from './App';  
      4.   
      5. it('renders without crashing', () => {  
      6.  const div = document.createElement('div');  
      7.  ReactDOM.render(<App />, div);  
      8.  ReactDOM.unmountComponentAtNode(div);  
      9. });  
  • JSON

    • This file is used to compile TypeScript into JavaScript.
      1. {  
      2.  "compilerOptions": {  
      3.    "baseUrl"".",  
      4.    "outDir""build/dist",  
      5.    "module""esnext",  
      6.    "target""es5",  
      7.    "lib": ["es6""dom"],  
      8.    "sourceMap"true,  
      9.    "allowJs"true,  
      10.    "jsx""react",  
      11.    "moduleResolution""node",  
      12.    "rootDir""src",  
      13.    "forceConsistentCasingInFileNames"true,  
      14.    "noImplicitReturns"true,  
      15.    "noImplicitThis"true,  
      16.    "noImplicitAny"true,  
      17.    "importHelpers"true,  
      18.    "strictNullChecks"true,  
      19.    "suppressImplicitAnyIndexErrors"true,  
      20.    "noUnusedLocals"true  
      21.  },  
      22.  "exclude": [  
      23.    "node_modules",  
      24.    "build",  
      25.    "scripts",  
      26.    "acceptance-tests",  
      27.    "webpack",  
      28.    "jest",  
      29.    "src/setupTests.ts"  
      30.  ]  
      31. }  

Summary

This was all about creating React application using TypeScript. To get more hands on this, please visit here.