Shallow Copy vs Deep Copy in React State :👈 👉:How to Type React Event Handlers

TypeScript Props for React Components

TypeScript Props for React Components

1. Introduction

In React, Props (Properties) are used to pass data from a parent component to a child component.

When using TypeScript with React, we define the expected types of props so that components receive the correct data.

TypeScript helps us:

  • Identify incorrect prop types during development.
  • Make components easier to understand and maintain.
  • Provide better IntelliSense and autocomplete.
  • Prevent missing required props.
  • Define optional props and default values.

2. Defining Props Using a Type

The simplest way to define props is by using a TypeScript type.

Example

type UserProps = {
    name: string;
    age: number;
};
function User(props: UserProps) {
    return (
        <div>
            <h2>{props.name}</h2>
            <p>Age: {props.age}</p>
        </div>
    );
}
function App() {
    return (
        <User name="John" age={25} />
    );
}
export default App;

Explanation:

  • UserProps defines the expected properties.
  • name must be a string.
  • age must be a number.
  • The User component accepts props of type UserProps.
  • TypeScript reports an error if the supplied values have incorrect types.

3. Defining Props Using an Interface

We can also use an interface to define component props.

Example

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

Both type and interface can be used to define React component props.

Type vs Interface

Feature type interface
Object props Supported Supported
Extending Using intersection (&) Using extends
Union types Supported Not directly supported
Declaration merging Not supported Supported

Which should you use?

Both are good choices. Use the one that best fits your project conventions. Use type when you need unions or intersections, and interface when you want an extendable object contract.

4. Optional Props

Sometimes a component does not require every prop. We can make a prop optional by using the ? symbol.

Example

interface UserProps {
    name: string;
    age?: number;
}
function User({ name, age }: UserProps) {
    return (
        <div>
            <h2>{name}</h2>
            <p>Age: {age ?? "Not provided"}</p>
        </div>
    );
}
// Both usages are valid
<User name="John" age={25} />
<User name="David" />

Here, name is required, but age is optional.

5. Default Values for Props

In modern React function components, we can provide default values through JavaScript parameter destructuring.

Example

interface UserProps {
    name: string;
    role?: string;
}
function User({
    name,
    role = "Guest"
}: UserProps) {
    return (
        <div>
            <h2>{name}</h2>
            <p>Role: {role}</p>
        </div>
    );
}
// Uses the default role
<User name="John" />
// Uses the supplied role
<User name="David" role="Admin" />

If the parent does not provide role, the component uses "Guest".

Note: A default value does not make a required prop optional. Use ? when the parent is allowed to omit that prop.

6. Passing Different Data Types as Props

React components can receive strings, numbers, booleans, arrays, objects, and other values through props.

Example

interface ProductProps {
    name: string;
    price: number;
    available: boolean;
    tags: string[];
    details: {
        category: string;
        brand: string;
    };
}
function Product({
    name,
    price,
    available,
    tags,
    details
}: ProductProps) {
    return (
        <div>
            <h2>{name}</h2>
            <p>Price: {price}</p>
            <p>Available: {available ? "Yes" : "No"}</p>
            <p>Category: {details.category}</p>
            <p>Brand: {details.brand}</p>
            <p>Tags: {tags.join(", ")}</p>
        </div>
    );
}
function App() {
    return (
        <Product
            name="Laptop"
            price={55000}
            available={true}
            tags={["Electronics", "Computer"]}
            details={{
                category: "Electronics",
                brand: "Example"
            }}
        />
    );
}

7. Passing Functions as Props

In React, parent components often pass functions to child components. This allows a child to notify its parent when an event occurs.

We can define the function type using TypeScript.

Example

interface ButtonProps {
    onClick: () => void;
}
function CustomButton({ onClick }: ButtonProps) {
    return (
        <button onClick={onClick}>
            Click Me
        </button>
    );
}
function App() {
    const handleClick = () => {
        alert("Button clicked");
    };
    return (
        <CustomButton onClick={handleClick} />
    );
}

Explanation:

  • onClick: () => void means the prop accepts a function with no arguments and no meaningful return value.
  • The parent defines the function.
  • The child receives and executes it when the button is clicked.

Function with Parameters

interface UserProps {
    onSelect: (userId: number) => void;
}
function User({ onSelect }: UserProps) {
    return (
        <button onClick={() => onSelect(101)}>
            Select User
        </button>
    );
}
function App() {
    const handleSelect = (userId: number) => {
        console.log("Selected User:", userId);
    };
    return <User onSelect={handleSelect} />;
}

Here, the callback accepts a number and returns no meaningful value.

8. Typing React Event Props

When passing event handlers as props, we can use React's event types.

Example: Input Change Event

import type { ChangeEvent } from "react";
interface InputProps {
    onChange: (event: ChangeEvent<HTMLInputElement>) => void;
}
function CustomInput({ onChange }: InputProps) {
    return (
        <input type="text" onChange={onChange} />
    );
}
function App() {
    const handleChange = (
        event: ChangeEvent<HTMLInputElement>
    ) => {
        console.log(event.target.value);
    };
    return <CustomInput onChange={handleChange} />;
}

Common React event types include:

  • ChangeEvent<HTMLInputElement> – input changes.
  • ChangeEvent<HTMLSelectElement> – select changes.
  • MouseEvent<HTMLButtonElement> – mouse events on buttons.
  • FormEvent<HTMLFormElement> – form events.
  • KeyboardEvent<HTMLInputElement> – keyboard events on inputs.

9. Using ReactNode for Children Props

Sometimes a component needs to receive content between its opening and closing tags.

For example:

<Card>
    <h2>Welcome</h2>
    <p>This is a card component.</p>
</Card>

We can type this content using ReactNode.

Example

import type { ReactNode } from "react";
interface CardProps {
    children: ReactNode;
}
function Card({ children }: CardProps) {
    return (
        <div>
            {children}
        </div>
    );
}
function App() {
    return (
        <Card>
            <h2>Welcome</h2>
            <p>This is a card component.</p>
        </Card>
    );
}

ReactNode allows React-renderable content, including elements, strings, numbers, fragments, and arrays of renderable content.

10. Extending HTML Element Props

Sometimes we create custom components that should support all the normal HTML attributes of an element.

For example, a custom button may need to support:

  • disabled
  • type
  • className
  • onClick

Instead of defining all these properties manually, we can extend React's built-in button attributes.

Example

import type { ComponentProps } from "react";
interface CustomButtonProps
    extends ComponentProps<"button"> {
    label: string;
}
function CustomButton({
    label,
    ...buttonProps
}: CustomButtonProps) {
    return (
        <button {...buttonProps}>
            {label}
        </button>
    );
}
function App() {
    return (
        <CustomButton
            label="Save"
            disabled={false}
            type="button"
            onClick={() => console.log("Saved")}
        />
    );
}

Explanation:

  • ComponentProps<"button"> obtains the props supported by a standard HTML button.
  • label is an additional custom prop.
  • ...buttonProps forwards the remaining HTML button properties.

11. Union Types in Props

Union types restrict a prop to a specific set of allowed values.

Example

type ButtonProps = {
    label: string;
    variant: "primary" | "secondary" | "danger";
};
function Button({ label, variant }: ButtonProps) {
    return (
        <button data-variant={variant}>
            {label}
        </button>
    );
}
// Valid
<Button label="Save" variant="primary" />
<Button label="Cancel" variant="secondary" />
// TypeScript error: "success" is not allowed
<Button label="Submit" variant="success" />

This is useful when a component supports a limited number of predefined options.

12. Discriminated Union Props

Discriminated unions allow a component to accept different sets of properties depending on a particular prop value.

Example

type PaymentProps =
    | {
        paymentType: "card";
        cardNumber: string;
    }
    | {
        paymentType: "upi";
        upiId: string;
    };
function Payment(props: PaymentProps) {
    if (props.paymentType === "card") {
        return <p>Card: {props.cardNumber}</p>;
    }
    return <p>UPI: {props.upiId}</p>;
}
// Valid
<Payment
    paymentType="card"
    cardNumber="1234"
/>
<Payment
    paymentType="upi"
    upiId="user@example"
/>

TypeScript understands which properties are available based on the value of paymentType.

13. Readonly Props

We can use readonly to prevent a prop property from being reassigned within the component.

Example

interface UserProps {
    readonly id: number;
    name: string;
}
function User({ id, name }: UserProps) {
    // Allowed
    console.log(name);
    // TypeScript error
    // id = 200;
    return <p>{id} - {name}</p>;
}

readonly provides a compile-time restriction. It does not freeze the object at runtime.

14. Common Mistakes When Typing React Props

  1. Using any everywhere: Avoid any because it removes much of TypeScript's type checking.
  2. Making every prop optional: Keep required properties required so missing data is detected.
  3. Using the wrong event type: Choose the correct React event type for the HTML element.
  4. Forgetting children: Define a children prop when the component expects nested content.
  5. Incorrect callback types: Define the expected parameters and return type of callback props.
  6. Confusing type checking with runtime validation: TypeScript does not automatically validate data received from an API.

15. Best Practices

  • Define clear prop types using type or interface.
  • Use meaningful property names.
  • Keep required and optional props clearly separated.
  • Use union types for predefined values such as button variants or status values.
  • Use ReactNode for flexible children content.
  • Use ComponentProps when extending standard HTML element props.
  • Define callback function signatures explicitly.
  • Avoid unnecessary use of any.
  • Validate external API data at runtime when necessary; TypeScript types alone do not validate it.

16. Interview Questions and Answers

Q1. What are props in React?

Props are inputs passed from a parent component to a child component. They allow components to receive and display dynamic data.

Q2. Why do we use TypeScript with React props?

TypeScript defines the expected data types of props and helps detect incorrect values during development.

Q3. What is the difference between type and interface?

Both can define object-shaped props. Interfaces support declaration merging and extension using extends. Types also support unions and intersections.

Q4. How do you define optional props?

Use the question mark (?) after the property name.

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

Q5. How do you pass a function as a prop?

Define the function signature in the props type.

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

Q6. What is ReactNode?

ReactNode represents content that React can render, such as elements, strings, numbers, and fragments.

Q7. How do you type children in React?

Import ReactNode from React and define the children property.

import type { ReactNode } from "react";
interface Props {
    children: ReactNode;
}

Q8. How do you extend HTML button properties?

Use ComponentProps<"button"> or the appropriate button attribute type from React.

Q9. What is a union type in React props?

A union type allows a prop to accept one of a predefined set of types or values.

type Props = {
    status: "loading" | "success" | "error";
};

Q10. Does TypeScript validate API response data at runtime?

No. TypeScript checks types during development and compilation. Runtime validation requires an additional validation mechanism, such as Zod.

17. Key Takeaways

  • Props allow parent components to pass data to child components.
  • Use type or interface to define prop types.
  • Use ? for optional props.
  • Use destructuring to access props conveniently.
  • Use function signatures to type callback props.
  • Use React event types for event handler props.
  • Use ReactNode for children content.
  • Use ComponentProps to reuse standard HTML element prop types.
  • Use union and discriminated union types for components with different variants.

Remember: TypeScript props define the contract between parent and child components. A well-defined prop interface makes React components safer, reusable, and easier to maintain.

🔙
Shallow Copy vs Deep Copy in React State :👈 👉:How to Type React Event Handlers

Comments and Discussion