Lesson 53 of 60 – TypeScript with React
88%

TypeScript with React

TypeScript with React combines React's component-based development approach with TypeScript's static type checking. TypeScript helps developers define the types of props, state, events, functions, and other values used in React applications.

Note: React applications can be written using JavaScript or TypeScript. TypeScript files commonly use .tsx when they contain JSX.

1. What is React?

React is a JavaScript library used to build user interfaces using reusable components.

function Welcome() {
    return <h1>Welcome to React</h1>;
}

2. What is TypeScript with React?

TypeScript with React means using TypeScript to add type information to React components and application code.

function Welcome(): JSX.Element {
    return <h1>Hello</h1>;
}

TypeScript can help identify many type-related mistakes during development.

3. TypeScript React File Extension

React components containing JSX are commonly stored in .tsx files when using TypeScript.

  • .ts → TypeScript without JSX.
  • .tsx → TypeScript with JSX.

4. Why Use TypeScript with React?

TypeScript can make React applications easier to maintain by describing the expected types of data.

  • Better type checking.
  • Better editor support.
  • Safer component development.
  • Improved code readability.
  • Useful for larger applications.

5. React Component with TypeScript

function App() {
    return (
        <div>
            <h1>My React App</h1>
        </div>
    );
}

export default App;

This component can be placed in a .tsx file.

6. Basic TypeScript Function Component

function Welcome(): JSX.Element {
    return <h1>Welcome</h1>;
}

The return type describes the type of value returned by the component.

7. Using React.FC

React.FC can be used to type a functional component.

import React from "react";

const Welcome: React.FC = () => {
    return <h1>Welcome</h1>;
};

Modern React code often uses ordinary function components with explicitly typed props instead of relying on React.FC.

8. TypeScript and JSX

JSX allows HTML-like syntax to be written inside JavaScript or TypeScript code.

function App() {
    const title: string = "My Application";

    return <h1>{title}</h1>;
}

9. Typed Variables in Components

TypeScript variables can be explicitly typed inside React components.

function App() {
    const name: string = "Rahul";
    const age: number = 20;

    return (
        <div>
            <h2>{name}</h2>
            <p>Age: {age}</p>
        </div>
    );
}

10. Type Inference in React

TypeScript can often determine the type automatically.

function App() {
    const name = "Amit";
    const age = 21;

    return <h1>{name} - {age}</h1>;
}

TypeScript infers name as a string and age as a number.

11. Typing Component Props

Props can be described using an interface or type alias.

interface UserProps {
    name: string;
    age: number;
}

12. Component with Typed Props

interface UserProps {
    name: string;
    age: number;
}

function User({ name, age }: UserProps) {
    return (
        <div>
            <h2>{name}</h2>
            <p>Age: {age}</p>
        </div>
    );
}

13. Passing Typed Props

<User
    name="Rahul"
    age={20}
/>

TypeScript checks that the values supplied to the component match the defined prop types.

14. Optional Props

The ? symbol can make a prop optional.

interface UserProps {
    name: string;
    age?: number;
}

The age prop can now be omitted.

15. Typed Component Children

React components can also receive children. In TypeScript, the children value can be typed using React's appropriate child type.

import { ReactNode } from "react";

interface CardProps {
    children: ReactNode;
}

function Card({ children }: CardProps) {
    return <div>{children}</div>;
}

16. Typed useState

React's useState hook can work with TypeScript types.

import { useState } from "react";

function Counter() {
    const [count, setCount] = useState<number>(0);

    return (
        <button onClick={() => setCount(count + 1)}>
            {count}
        </button>
    );
}

17. Typed String State

const [name, setName] = useState<string>("");

This state is designed to contain string values.

18. Typed Boolean State

const [isLoggedIn, setIsLoggedIn] =
    useState<boolean>(false);

The state stores a boolean value such as true or false.

19. Typed Array State

const [students, setStudents] =
    useState<string[]>([]);

setStudents(["Rahul", "Priya", "Amit"]);

The state is typed as an array of strings.

20. Typed Object State

interface User {
    name: string;
    age: number;
}

const [user, setUser] =
    useState<User | null>(null);

The state can contain a User object or null.

21. Typed Event Handler

TypeScript can type React events so that event-related properties are handled correctly.

function handleClick(
    event: React.MouseEvent<HTMLButtonElement>
): void {
    console.log(event.currentTarget);
}

22. Typed Input Change Event

function handleChange(
    event: React.ChangeEvent<HTMLInputElement>
): void {
    console.log(event.target.value);
}

This is useful when handling text input in React forms.

23. Typing Component Functions

Functions passed to components can also be given explicit types.

interface ButtonProps {
    onClick: () => void;
}

function MyButton({ onClick }: ButtonProps) {
    return (
        <button onClick={onClick}>
            Click Me
        </button>
    );
}

24. TypeScript and React Component Reusability

Typed props make reusable components more predictable.

interface ButtonProps {
    text: string;
    disabled: boolean;
}

function Button({ text, disabled }: ButtonProps) {
    return (
        <button disabled={disabled}>
            {text}
        </button>
    );
}

25. TypeScript with React Forms

import { useState } from "react";

function LoginForm() {
    const [email, setEmail] = useState<string>("");

    return (
        <input
            value={email}
            onChange={(e) =>
                setEmail(e.target.value)
            }
        />
    );
}

26. TypeScript Error Checking

TypeScript can detect values that do not match the expected type.

let age: number = 20;

// Error
// age = "twenty";

Similar type checking can be applied to React props, state, functions, and events.

27. React Component with Interface

interface StudentProps {
    id: number;
    name: string;
    course: string;
}

function Student({
    id,
    name,
    course
}: StudentProps) {

    return (
        <div>
            <h2>{name}</h2>
            <p>ID: {id}</p>
            <p>Course: {course}</p>
        </div>
    );
}

28. Complete Small React + TypeScript Example

import { useState } from "react";

interface Student {
    name: string;
    course: string;
}

function App() {

    const [student, setStudent] =
        useState<Student>({
            name: "Rahul",
            course: "React"
        });

    return (
        <div>
            <h1>{student.name}</h1>
            <p>{student.course}</p>
        </div>
    );
}

export default App;

29. TypeScript with React and React Native

The same TypeScript concepts are useful when moving from React web development to React Native. Props, state, functions, objects, events, API responses, and reusable components can all be typed.

interface User {
    id: number;
    name: string;
}

function UserInfo({ user }: { user: User }) {
    return <h2>{user.name}</h2>;
}

30. Complete React + TypeScript Example

import { useState } from "react";

interface Student {
    id: number;
    name: string;
    course: string;
}

interface StudentCardProps {
    student: Student;
}

function StudentCard({
    student
}: StudentCardProps) {

    return (
        <div>
            <h2>{student.name}</h2>
            <p>ID: {student.id}</p>
            <p>Course: {student.course}</p>
        </div>
    );
}

function App() {

    const [student] = useState<Student>({
        id: 101,
        name: "Rahul",
        course: "React Native"
    });

    return (
        <div>
            <h1>Student Details</h1>

            <StudentCard
                student={student}
            />
        </div>
    );
}

export default App;

This example demonstrates a typed object, typed component props, typed state, and a reusable React component.

📌 Key Points

  • TypeScript can be used to build strongly typed React applications.
  • React components containing JSX commonly use the .tsx extension.
  • Props can be typed using interfaces or type aliases.
  • React state can be given explicit TypeScript types.
  • TypeScript can type arrays, objects, strings, numbers, and booleans.
  • React event handlers can also be typed.
  • Typed props make reusable components more predictable.
  • TypeScript helps identify many type-related mistakes during development.
  • The same TypeScript concepts are useful for React Native development.
  • TypeScript is especially useful when React applications become larger and more complex.

🧠 Quick Quiz

Question: Which file extension is commonly used for a TypeScript React component containing JSX?