How to Use React TypeScript?

Learn via video courses
Topics Covered

Overview

TypeScript is a superset of JavaScript which makes a lot of sense when used with React because TypeScript allows for strongly typed JavaScript code with various code IntelliSense.

Introduction

Using react typescript allows us to take advantage of IntelliSense, in supported IDEs like VS code, and detect error before compiling the code.

Since TypeScript is a superset of JavaScript and cannot run on its own and needs to be compiled to JavaScript to run, adopting react typescript is relatively easier because React is essentially a JavaScript library for creating user interfaces.

This is because when upgrading a React project to TypeScript, the files can be incrementally upgraded without causing any change with the rest of the project.

Prerequisites

In order to setup React with TypeScript, below are the prerequisites:

  • npm should be installed
    • typescript should be installed
    • react should be installed
    • react-dom should be installed

What is React?

React is a front-end development library which allows for reusable component which 'react' to any change in the UI.

React with its intuitive features and modularity makes it easier to understand. Large website designs can be broken down into smaller components. It has features like Routing, State management using Redux and resuability of components which makes it very popular among front end developers.

Is React better with TypeScript?

There are various advantages of using React with TypeScript over JavaSript, some of the bigger advantages are:

1. Variable and bug checks

TypeScript can identify bugs before even compiling the code using the IntelliSense which saves us a lot of time.

2. Readable, easily understandable code

Since TypeScript is a strongly typed language, there are types assigned for variables, functions, classes and properties which makes the code much more readable and easy to understand.

3. Interfaces

Complex type definitions can be defined using interfaces in TypeScript which allows strict type checks while writing complex object definitions.

4. Better support for JSX

TypeScript compiles JSX directly to JavaScript without the use of Babel.

5. IDE support

IDEs like VS Code make languages like TypeScript all the more powerful with code refactoring, code snippets extensions and real time type checking.

6. Support for existing React projects

Adopting TypeScript is easy, as files can be incrementally upgraded without causing issues throughout the rest of your project.

7. Community

TypeScript is an open source language used by millions of developers around the world and that community of developers makes TypeScript easy to find answers to your queries.

Understanding .tsx files in Typescript

The .tsx files in react typescript were introduced several releases after the initial release to enable JSX in TypeScript files.

1. Difference between .ts and .tsx in TypeScript

There are 2 major differences between .tsx and .ts files:

  • .tsx files uses as as the default way while type casting as opposed to using <> in .ts files
  • .tsx files also enables JSX support in TypeScript.

VS Code Extensions

  • TypeScript Hero: Additional tooling for TypeScript
  • TypeScript Importer: Automatically searches for TypeScript definitions in workplace files and provide all known symbols as completion item to allow code completion.
  • TypeScript React Code Snippets: Code snippets for React in TypeScript.
  • TypeScript Debugger: TypeScript debug configuration for VS Code
  • Move TS: Extension for moving TypeScript files and folders and updating relative imports in workspace projects.

React + TypeScript Starter Kits

1. Cloud setups

Cloud setups provide react typescript playground with React which provides you with index.tsx file with a proper file structure in place. This index.tsx file is the entry point to the project.

  • CodeSandbox

    • CodeSandbox is an online editor for web applications
    • It provides a TypeScript + React combination with all the folder structure and dependencies already taken care of
      • public folder contains the index.html
      • and src folder contains the index.tsx files which is the entry point to the project

2. Local dev setup

Create React App

  • Create React App (CRA) supports TypeScript natively.
    • --typescript flag when used with create-react-app creates a React project with TypeScript instead of JavaScript.

How does TypeScript Compile React Code?

  • TypeScript compiles React code based on the configurations specified for the tsc compiler in tsconfig.json file present in the root directory of the project
    • when tsc compiler is invoked without any input configuration file path as parameter, it looks for the tsconfig.json file in the root directory for configurations.
    • when tsc compiler is invoked with a -p or --project flag followed by a file path to an input configuration, it ignores the default tsconfig.json file.
  • The tsconfig.json file has a root level property called compilerOptions that specifies the compiler options like:
    • outDir: output folder after compilation
    • target: specifies the JavaScript engine (es5, es6 or next)
    • jsx: which takes react as its value, meaning JSX files will be compiled as React files.

Configuring Webpack for React and TypeScript

  • webpack is a module bundler that compiles JavaScript modules
    • ts-loader is a webpack plugin which is TypeScript loader for webpack, essentially making webpack easier to use with TypeScript.
  • webpack.config.js has rules defined inside of it that allows webpack to compile all .ts and .tsx files through the ts-loader and output bundle.js file in the destination folder.

Adding NPM Scripts

  • Adding npm scripts allows you to configure npm commands to invoke webpack which will create a bundle.
  • this is done so by updating the package.json file in the project root directory:
  • now invoking npm run bundle will create a bundle by invoking webpack

Creating the index.tsx File

  • index.tsx file is the entry point for our React project.
  • index.tsx file is created inside a folder caller src and add the following code:
  • Now running the command npm run build will create a bundle.js file in the destination folder which can be referenced in an index.html to render the jsx.

Creating React Components in TypeScript

There are two ways in which components can be declared in React:

1. Functional Components

  • React.FunctionComponent is used to define functional React components in TypeScript
  • object structure for expected props are mentioned in the component declaration.
  • The object structure can be declared in one of two ways:
    • Inline declaration
    • by creating an interface

2. Class Based Components

  • class component follows a declaration type similar to the functional components
  • class components extend React.Component class with state and props defined as interfaces.

Conclusion

  • TypeScript makes React more efficient and resuable

  • TypeScript files can be compiled in React by configuring webpack using ts-loader which results in a final build.

  • TypeScript is a strongly typed version of JavaScript meaning we can define types for almost anything, even, objects. Defining type constraints for objects can mean no error while parsing objects returned from API calls in React.

  • The easiest to get started with TypeScript and React use React's create-react-app toolchain which allows you to create single page React applications

    • npm, the node pacakage manager should be installed before
    • To set up a TypeScript project in React using create-react-app use the command below in the terminal:
  • TypeScript also supports both Class based and Function based components in React