TypeScript in React

#day3learningReact

Introduction:

TypeScript is just the addition of types to JavaScript. It is said to be a syntactic superset of JS. JavaScript is a loosely typed language, which means you do not specify the data type. The problem comes in when you pass arguments in a function and you do not have clarity about which data type value the function parameters are meant to accept and return the result.

function sum(obj){
    return obj.a + obj.b;
}

const result1=sum({a:5,b:9})
const result2=sum({a:"david",b:"warner"})
console.log(result1)
console.log(result2)

Here the sum() function is intended to accept integer values and return the addition of values as a result. Since the JS is loosely typed it creates chaos as to which type of values are supposed to be sent in function call arguments. It also accepts strings and returns concatenated strings as a result.

Here the typescript comes into play, it is used to specify the data type and it reports the error if the data type is unmatched.

interface Myobj{
    a:number;
    b:number
}
function add(obj:Myobj){
    return obj.a+obj.b;
}

const result = add({a:4,b:5})
console.log (result)

The output is the addition of two values i.e. '9'. If you try to pass a string as an argument it throws a type error.

It says Myobj.a is of type integer and hence string value is not accepted.

Using TypeScript in React:

To use TypeScript in React we need to integrate TypeScript while creating the React Project.

  • Install TypeScript on your local machine.

      npm -i g typescript
    
  • Create React project in your desired folder.

      npx create-react-app hello-ts --template typescript
    

The default folder structure will be created with some of the files having a .tsx extension i.e. typescript extension.

Creating Components in React with TypeScript:

Let us create a basic component that extends React's Functional Component Interface. Create new folder components in src folder within which create new files named 'index.tsx' and 'index.css'.

import React from "react";
import './index.css';

export const TodoList:React.FC= ()=>{
    return (
        <div className="container">
            <ol>
                <li>home work</li>
                <li>Article writing</li>
                <li>Coding</li>
                <li>Learn React</li>
            </ol>
        </div>
    )
};
.container{
    border: 1px dashed rgb(72, 72, 114);
    background-color: aqua;
    width: 200px;
    padding:10px;
    display: flex;
    margin: auto;
    margin-top: 40px;
    font-size: larger;
}

Here Component TodoList extends React.FC i.e. Functional Component which is React's built-in interface, specifies the type as Function. If the TodoList does not return a react element it throws an error as shown below.

Hence, TypeScript helps prevent certain types of errors by enforcing type safety and providing stricter checks during development.

Now render the TodoList component in the main index.tsx file.

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import { TodoList } from './components/Todo';

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <TodoList/>
    <TodoList/>
    <TodoList/>
    <TodoList/>
  </React.StrictMode>
);

The Web Page will appear as follows:

Result: