Getting started with React and TypeScript

By StartxLabs
Date 08-06-21
Getting started with React and TypeScript
" Getting started with React and TypeScript"

 

What is TypeScript?

 

TypeScript is a typed superset of JavaScript, that makes the React components more resilient without complex building and coding. It works on all browsers and OS and assists in reducing compile-time errors. All the features of JavaScript are available in TypeScript as TypeScript is a superset of it. Some of the most important features of TyoeScript which aid in efficient development include code refactoring, type checking, navigation features and so on.

 

Features that TypeScript adds to ReactJs

 

There are many advanced features added to ReactJs, that enable easy and efficient development in React. Some of the important features added by TypeScript are,

 

  • Strongly types tuples and arrays

  • Reusable types with generics

  • Type annotations and inference

  • The never and unknown type

  • Union and Intersection types

 

Why use TypeScript with React?

 

You may even ask, "why should I use TypeScript in React when JS is available? What are all the benefits I can get?". Let's go for the answers to this question now.

 

  • Imagine typing a long paragraph for your friend on your mobile. If your keyboard keeps on giving you suggestions, will you complete typing much faster right? That's the same here. TypeScript will provide you options and suggestions while developing code for your application in React, which makes your development process much easier and faster.

  • Imagine the same situation, but now besides providing suggestions, it also highlights your errors and insists that you correct them. You will type much faster and you need not read the whole passage for correcting errors right?  Like that, TypeScript highlights your errors and typos before running them, which enables us to save time we spend on fixing bugs and maintain consistent code. This error-correction feature makes TypeScript the most favorite of all the React developers.

  • Using TypeScript, we can add types to functions, properties, and variables that make the code understandable to us. By using this we can read and understand the code much easier.

  • TypeScript enables refactoring of the code and makes the updation without making any changes to its behaviors. It also improves the features of JS and it is compatible with any browser.

 

Read our article on - Why is React Native the best for Mobile App Development?

 

How to get started using TypeScript?

 

You can start using TypeScript by using the Create React App developed by Facebook by importing the create-react-app npm package. The CRA will provide many built-in features, Webpack, hot reloading development that assist you during the entire development process.

 

To ensure type-checked tests don't make a mismatch between the development editor and CRA's output, another npm script known as "test:tsc": "tsc -p tsconfig.test.json -w" should be used. After the completion of type-checking tests, you can now successfully start creating your app using React using TypeScript.

 

  • To use CRA, npx create-react-app my-app --template typescript command should be run.  For this, you need the latest version 5.2 of Node.js and npm, a code editor, and CRA.

  • After that, some extensions such as .tsx, tsconfig.json, react-app-env.d.ts should be used. Here tsx stands for TypeScript JSX.

  • After this, run it in development mode by running the start npm script.

  • To set up ESLint and Prettier, install the dependencies

    • yarn add eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-react --dev

  • At root, create the .eslintrc.js file

  • Add Prettier dev dependencies

    • yarn add prettier eslint-config-prettier eslint-plugin-prettier --dev

  • At root, create .prettierrc.js file

  • Update the files.

  • Followed by that, update the .vscode/settings.json (allows you to fix your code before running)

  • While creating interfaces, follow the react-typescript-cheatsheet guidelines.

  • While developing an application in React using TypeScript uses descriptive comments

  • TypeScript also involves the usage of hooks. It takes the value given by the useState hook. It also makes use of the useReducer hook to implement discriminated unions.

 

There are two types using which you can build your application using TypeScript. One is using the Parcel, another is the Webpack. You can use TypeScript with classes, functional components, and also with props.

 

Functional Component

 

import * as React from 'react';

const Count: React.FunctionComponent<{
  count: number;
}> = (props) => {
  return <h1>{props.count}</h1>;
};

export default Count;

 

 

This function is written to define object the structure of the props. It can also be done using the following:

 

interface Props {
  count: number;
}

const Count: React.FunctionComponent<Props> = (props) => {
  return <h1>{props.count}</h1>;
};

 

 

Read our article on - Custom Tab Bar in React Native using SVG, and D3-Shape

 

Class Component

 

Class components can be created by using TypeScript like -

 

import * as React from 'react';

import Count from './Count';

interface Props {}

interface State {
  count: number;
};

export default class Counter extends React.Component<Props, State> {
  state: State = {
    count: 0
  };

  increment = () => {
    this.setState({
      count: (this.state.count + 1)
    });
  };

  decrement = () => {
    this.setState({
      count: (this.state.count - 1)
    });
  };

  render () {
    return (
      <div>
        <Count count={this.state.count} />
        <button onClick={this.increment}>Increment</button>
        <button onClick={this.decrement}>Decrement</button>
      </div>
    );
  }
}

 

Default Props

 

By using default props, we can develop our code in TypeScript like -

 

import * as React from 'react';

interface Props {
  count?: number;
}

export default class Count extends React.Component<Props> {
  static defaultProps: Props = {
    count: 10
  };

  render () {
    return <h1>{this.props.count}</h1>;
  }
}

render () {
  return (
    <div>
      <Count />
      <button onClick={this.increment}>Increment</button>
      <button onClick={this.decrement}>Decrement</button>
    </div>
  )
}

 

 

"We transform your idea into reality, reach out to us to discuss it.

Or wanna join our cool team email us at [email protected] or see careers at Startxlabs."

 

subscribe to startxlabs

startxlabs