HOW TO BUILD REACT APPS WITH TYPESCRIPT

5min Oct 26, 2021 Somendra Yadav MOBILE Views : 2126
HOW TO BUILD REACT APPS WITH TYPESCRIP
Typescript isn't a new language but is part of Javascript as a superset. Therefore, any valid Javascript code is also known as a valid Typescript code. Typescript, however, includes additional features that aren't available in the present version of Javascript.

In Typescript, there is a concept of strong or static typing. When working with languages such as Java, you need to specify the variable however with Typescript you don't need to type in the variable. But using this feature allows the application to become easier to debug in case something goes wrong.

Through Typescript, you can catch errors quickly in a compile-time rather than a run time. Not all of them can be caught, but most of them are through run time. When we compile our Typescript code, catching the error becomes easier before you set out to deploy your application. Typescript allows access to amazing tools that help make it easier.

Installing typescript in a step-by-step procedure

Given below are the steps to install Typescript on your computer through npm:

INSTALL NODE.JS

Use the LTS variant to install Node.js onto your computer. In case you’re advised to install another version of Node.js, do so. But it is recommended to install the latest version for better usage. To check if it’s installed, go to your cmd and type in node  -v. If the program is installed properly then you will get a reply of the current version running; v12.16.1.

INSTALL TYPESCRIPT

To install typescript, open your cmd and type in npm install  -g typescript  to install Typescript globally. In case you are using a Mac, type “sudo” before npm. To check and see if Typescript is installed, you will need to type in tsc  -v in your cmd and you will get the current version running on your computer.

MAKE A FILE WITH A .TS EXTENSION

Create a file that has a .ts extension and type in any javascript that you want. You will need to name the file and you can choose to use Notepad++ to simply type in your Javascript.

Also Read: Xamarin: .NET MAUI

TRANSLATE YOUR .TS TO A .JS FILE

Typescript may be like Javascript but it’s more advanced so, you will need to translate your .ts file into a .js file to make it a regular Js. To do so, go to your recently created .ts file and type in tsc filename.ts. Through this, a copy of your file will be created in a .js version. The new version contains the code you wrote, but rather than being in Transcript, it’s converted to Javascript.

In some cases, the code may be similar if you didn’t use any Transcript features but with other cases, there may be major changes to the code.

A Few Unique Features Of Transcript

Typescript has numerous fantastic capabilities that expand JavaScript in useful ways, such as the ability to specify an object's structure in a number of ways. You'll likely come across a lot of alternatives in your hunt for the best method to describe objects, the most prevalent of which being class and interface.  

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}
let greeter = new Greeter('world')

When you wish to enforce structural contracts (i.e. what you want sent in or returned back), use the interface:

interface FullName{
    firstName: string;
    lastName: number;
}
const fullNameObj:FullName = {
    firstName: "Jon",
    lastName: "Snow"
}

DEFINING PROPS

It's vital to understand the multiple ways to create props, whether you're new to utilising Typescript with React or a seasoned veteran seeking to add more functional components to your codebase by introducing hooks.

One of the simplest methods to define props is to include them in the argument list of a function, as seen above. Consider the following example:

interface FullName {
    firstName: string;
    lastName: string;
}
function FunctionalComponent(props:FullName){
    // props.firstName
    // props.lastName
}
In most situations, the straightforward approach is sufficient. But what if you want to define default props in the event that they aren't provided? Or do you simply want your component's syntax to be cleaner?

Destructuring is a JavaScript syntactic feature that may be used in certain situations. This gives you greater freedom in how you define your props.

// Using the same FullName interface from the last example
function FunctionalComponent({firstName, lastName}:FullName){
    // firstName
   // lastName
}

What if you wanted to add a middle name to your child's name? Because hardly everyone has a middle name, you should leave it blank. Destructuring can be a simple solution to that issue.

interface OptionalMiddleName {
    firstName: string;
    middleName?: string;
    lastName: string;
}
function Component({firstName, middleName = "N/A", lastName}:OptionalMiddleName){
    // If middleName wasn't passed in, value will be "N/A"
}
Now, everytime you need to refer to middleName, you'll receive a lovely default "N/A" if it doesn't exist. Using the non-destructured syntax to provide the same functionality would look like this:

// using the same OptionalMiddleName interface from above
function Component(props:OptionalMiddleName){
    if(!props.middleName){
        props.middleName = "N/A"
    }
}

USING REACT.FC

Importing and using React's Functional Component type, or FC for short, provides another approach to specify props. Using the React framework. FC is more verbose, but it has certain advantages:

●    It is explicit about the sort of response it expects.
●    For static properties, type checking and autocomplete are provided (i.e displayName, defaultProps)
●    Gives a meaning of children that isn't explicitly stated:

const ReactFCComponent: React.FC<{title:string}> = ({children, title}) => {
        return <div title={title}>{children}</div>
    }

Adding Typescript To The React Application

Discussed below are the necessary steps one should follow in order to add Typescript to a React application.
 
Installation: You’ll first have to install React onto your computer. It is advised that you don’t use the global version as that doesn’t provide the latest version of npx.  Refrain from using the npm install -g create-react-app and instead use a website to carefully and securely install React.
 
Create a new project: To create a new project run the following commands -

npx create-react-app my-app --template typescript
# or
yarn create react-app my-app --template typescript

Rename: After that, rename any file to TypeScript. Make sure your development server is up to date and restart the server. Errors will surely appear when typing in the same console as the build one. So, you’ll need to configure your coding and fix these errors before you proceed with developing your project.

Getting started with Transcript and React through Facebook

With Facebook's own Create React App (CRA) site generator is the quickest method to get started using TypeScript with React. This will create a fully working React app with several common features such as Babel, Jest, Webpack, and a rapid reloading development server pre-installed.


First, make use of the create-react-app to create a new TypeScript project, use the npm package my-typescript-app:

# Generate a new React Typescript project
npx create-react-app my-typescript-app --typescript

# wait for installation to be done!
cd my-typescript-app


This will create a new folder called my-typescript-app in which your new project will be saved. While npm installs the needed dependencies, it may take a few minutes.

Simply rename your .js/.jsx files to .ts/.tsx and you can start using TypeScript right away:

# Rename js to ts
mv src/index.js src/index.ts
# Start development server and watch for changes
npm start


As you make changes to your project files, the app will automatically reload and reflect them.

TYPE CHECKING TESTS

Ensuring that your tests are type-checked is one issue that has yet to be fixed. CRA will execute TypeScript-based tests but will not display any TypeScript compiler errors, causing a mismatch between your development editor and the CRA test job output. It also implies that TypeScript failures in your tests won't prevent continuous integration builds from succeeding.
You may use an additional npm script to guarantee that tests are type-checked:
{
    "scripts": {
        "test:tsc": "tsc -p tsconfig.test.json -w"
    }
}

This will start the TypeScript compiler in "watch" mode right away. The -p option points to a new config file, tsconfig.test.json, in the project's root directory:
{
    "extends": "./tsconfig.json",
    "include": [
        "src/**/*.ts",
        "src/**/*.test.ts",
        "src/**/*.test.tsx",
    ],
}
While working on testing, you may now execute this new npm script:
npm run test:tsc

It's simpler to follow both instructions if your terminal or command prompt supports split outputs. Type checking support for your tests completes the TypeScript setup for CRA, allowing you a fully functioning TypeScript experience when creating React apps.

Getting Started With Typescript Through React From Scratch

Although CRA works well by incorporating Transcript through React, sometimes it’s necessary to start from scratch. However, starting at the bottom means making codes that are simple and effective.
Start by using npm to install all of the needed dependencies for a new TypeScript project with React support:

npm install react react-dom typescript @types/react @types/react-dom --save

After installing the packages, you'll need to create a new TypeScript tsconfig.json file that supports JSX and React:

{
  "compilerOptions": {
    // No module system, concatenated file
    "module": "none",

    // Set React as the JSX factory
    "jsx": "react",

    // Resolve modules using Node-resolution algorithm
    "moduleResolution": "node",

    // Target ES6 for more modern browsers
    "target": "es6",

    // Include typings from built-in lib declarations
    "lib": ["es2015", "dom", "dom.iterable"],

    // Include module source maps for debugging
    "sourceMap": true,

    // Output to single concatenated file
    "outFile": "dist/bundle.js"
  },
  "include": ["src"]
}

This creates a basic project configuration for React and React DOM support. In src, any TS or TSX files will be built.

To refer to other TypeScript files, you must use triple-slash directives, and global dependencies must be specified on the HTML page.

Create a new src/index.tsx file like follows:
/// <reference path="App.tsx" />

ReactDOM.render(<App />, document.getElementById("root"));
This will configure our React app's rendering using the App /> component in src/App.tsx:
const App = () => <div>Hello React App from scratch</div>;
We can now add some additional npm scripts to the package to create and monitor TypeScript. json document:
{
  "scripts": {
    "build": "tsc -p .",
    "watch": "tsc -p . -w"
  }
}
To create your app, run the following command:

npm run build

You May Also Like: Flutter vs Ionic vs React Native vs Xamarin

The dist/bundle.js file, which includes the concatenated code, will be generated as a result of this.
Create an index.html page in the project root with references to React and React DOM as browser packages, then you can use the generated bundle below:
<!DOCTYPE html>
<html>
  <head>
    <title>React and TypeScript</title>
  </head>
  <body>
    <div id="root"></div>

    <!-- Dependencies -->
    <script src="https://unpkg.com/react@16.8.2/umd/react.development.js" type="text/javascript"></script>
    <script src="https://unpkg.com/react-dom@16.8.2/umd/react-dom.development.js" type="text/javascript"></script>

    <!-- Compiled TypeScript -->
    <script src="dist/bundle.js" type="text/javascript"></script>
  </body>
</html>
Add a script> reference to the built bundle and other CDN package resources to the root element, which React will render within.

The serve npm package can now be used to preview the application:

npx serve

To view the basic application, go to the URL given in the console.

For small TypeScript projects, using triple-slash references works, but for online apps, there are a range of assets that should be packaged, such as CSS, pictures, and third-party packages. You'll probably want to introduce a module bundler and optimization tool at this point.

Bottom Line

If you’re looking to build a React application with Typescript, we have simplified the entire process for you in the form of a step-by-step guide above. It’s important for you to follow these steps in order to avoid any mistakes and repetitions.