How to Create Type-Safe Reusable Form Components :👈 👉:How to Avoid any in React Applications

How to Handle Optional Props in TypeScript

How to Handle Optional Props in React with TypeScript

1. What Are Optional Props?

In React, props are used to pass data from a parent component to a child component.

Sometimes a component does not need all its props every time it is used. In such cases, we can make certain props optional using the ? symbol in TypeScript.

Example:

type UserProps = {
    name: string;
    age?: number;
};
function User({ name, age }: UserProps) {
    return (
        <div>
            <p>Name: {name}</p>
            <p>Age: {age}</p>
        </div>
    );
}

Using the component:

<User name="John" age={25} />
<User name="David" />

Both usages are valid because age is optional.

  • name: string means name is required.
  • age?: number means age is optional.

2. Required Props vs Optional Props

Let's understand the difference.

type ProductProps = {
    id: number;
    name: string;
    price: number;
    description?: string;
    discount?: number;
};
Property Type Required?
idnumberYes
namestringYes
pricenumberYes
descriptionstringNo
discountnumberNo

Valid usage:

<Product
    id={1}
    name="Laptop"
    price={50000}
/>
<Product
    id={2}
    name="Mobile"
    price={20000}
    description="Android mobile"
    discount={10}
/>

Invalid usage:

<Product
    id={1}
    price={50000}
/>

This produces a TypeScript error because the required name property is missing.

3. Set Default Values for Optional Props

Sometimes an optional prop needs a default value when the parent component does not provide it.

We can use JavaScript destructuring defaults.

type ButtonProps = {
    label: string;
    color?: string;
    size?: string;
};
function Button({
    label,
    color = "blue",
    size = "medium"
}: ButtonProps) {
    return (
        <button>
            {label} - {color} - {size}
        </button>
    );
}

Using the component:

<Button label="Save" />
<Button
    label="Submit"
    color="green"
    size="large"
/>

Output:

  • First button uses the default color blue and size medium.
  • Second button uses the supplied color green and size large.

Important: Providing a default value does not make a required prop optional. The question mark ? is what makes a prop optional.

4. Optional Props with Null and Undefined

Optional properties and nullable properties are related, but they are not the same.

Optional Property (?)

type UserProps = {
    name?: string;
};

The name property can be omitted. If provided, it must be a string (or undefined when explicitly allowed by the TypeScript configuration).

Nullable Property

type UserProps = {
    name: string | null;
};

The name property is required, but its value can be a string or null.

Optional and Nullable Property

type UserProps = {
    name?: string | null;
};

Now the name property can be:

  • Omitted.
  • A string.
  • Null.
Declaration Can be omitted? Can be null?
name: stringNoNo
name?: stringYesNo
name: string | nullNoYes
name?: string | nullYesYes

5. Handle Optional Props Using Conditional Rendering

Sometimes we want to display a section only when an optional prop is provided.

type UserProps = {
    name: string;
    email?: string;
    phone?: string;
};
function User({ name, email, phone }: UserProps) {
    return (
        <div>
            <h2>{name}</h2>
            {email && (
                <p>Email: {email}</p>
            )}
            {phone && (
                <p>Phone: {phone}</p>
            )}
        </div>
    );
}

Using the component:

<User
    name="John"
    email="john@example.com"
/>
<User
    name="David"
    phone="9876543210"
/>

The component displays only the properties that are provided.

Note: For values where zero or an empty string is meaningful, use an explicit condition such as value !== undefined instead of relying on truthiness.

6. Optional Boolean Props

Boolean props are commonly used to control component behavior.

type ModalProps = {
    title: string;
    isOpen?: boolean;
    showCloseButton?: boolean;
};
function Modal({
    title,
    isOpen = false,
    showCloseButton = true
}: ModalProps) {
    if (!isOpen) {
        return null;
    }
    return (
        <div>
            <h2>{title}</h2>
            {showCloseButton && (
                <button>Close</button>
            )}
        </div>
    );
}

Using the component:

<Modal title="User Details" />
<Modal
    title="Settings"
    isOpen={true}
    showCloseButton={false}
/>

Here:

  • isOpen defaults to false.
  • showCloseButton defaults to true.
  • The component is hidden when isOpen is false.

7. Optional Props with ReactNode

Sometimes a reusable component needs optional content, such as a heading, icon, footer, or additional message.

We can use React's ReactNode type.

import { ReactNode } from "react";
type CardProps = {
    title: string;
    children?: ReactNode;
    footer?: ReactNode;
};
function Card({
    title,
    children,
    footer
}: CardProps) {
    return (
        <div>
            <h2>{title}</h2>
            {children && (
                <div>{children}</div>
            )}
            {footer && (
                <footer>{footer}</footer>
            )}
        </div>
    );
}

Using the component:

<Card title="User Profile">
    <p>Welcome to your profile.</p>
</Card>
<Card
    title="Notifications"
    footer={<button>View All</button>}
/>

Both children and footer are optional.

8. Inherit HTML Attributes and Add Optional Props

When creating reusable components, we often want to support standard HTML attributes along with our custom optional props.

For example, a reusable input component can accept all standard input attributes.

import {
    InputHTMLAttributes
} from "react";
type InputProps =
    InputHTMLAttributes<HTMLInputElement> & {
        label: string;
        error?: string;
        helperText?: string;
    };
function Input({
    label,
    error,
    helperText,
    ...props
}: InputProps) {
    return (
        <div>
            <label htmlFor={props.id}>
                {label}
            </label>
            <input {...props} />
            {helperText && (
                <p>{helperText}</p>
            )}
            {error && (
                <p role="alert">{error}</p>
            )}
        </div>
    );
}

Using the component:

<Input
    id="email"
    label="Email"
    type="email"
    placeholder="Enter email"
    helperText="Use your work email address"
/>
<Input
    id="password"
    label="Password"
    type="password"
    error="Password is required"
/>

Here:

  • label is required.
  • error is optional.
  • helperText is optional.
  • Standard HTML input properties are inherited through InputHTMLAttributes.

9. Optional Props with TypeScript Utility Types

TypeScript provides utility types that help us modify existing types.

Partial<T>

Partial makes all properties optional.

interface User {
    name: string;
    email: string;
    age: number;
}
type UserProps = Partial<User>;

Now all three properties are optional.

const user1: UserProps = {
    name: "John"
};
const user2: UserProps = {
    email: "john@example.com",
    age: 25
};

Required<T>

Required makes all properties required, even if they were originally optional.

interface User {
    name: string;
    email?: string;
    age?: number;
}
type CompleteUser = Required<User>;

Now name, email, and age are all required in CompleteUser.

Pick<T, K>

Pick selects specific properties from an existing type.

interface User {
    id: number;
    name: string;
    email: string;
    age: number;
}
type UserCardProps = Pick<User, "name" | "email">;

Omit<T, K>

Omit removes specific properties from an existing type.

interface User {
    id: number;
    name: string;
    email: string;
}
type UserProps = Omit<User, "id">;

These utility types are useful when building reusable components from existing interfaces.

10. Common Mistakes

1. Making Every Prop Optional

Avoid:

type ButtonProps = {
    label?: string;
    onClick?: () => void;
    disabled?: boolean;
};

If a button must have a label, making it optional can create unnecessary complexity.

Better:

type ButtonProps = {
    label: string;
    onClick?: () => void;
    disabled?: boolean;
};

2. Confusing Optional and Nullable Props

type Props = {
    name?: string;
};

This means the property can be omitted. It does not automatically mean that null is accepted.

3. Forgetting Default Values

function Button({ size }: { size?: string }) {
    return <button>{size}</button>;
}

If the component needs a default size, provide one through destructuring.

function Button({
    size = "medium"
}: {
    size?: string;
}) {
    return <button>{size}</button>;
}

4. Using Truthiness for Every Optional Value

Consider an optional numeric value:

{/* Can incorrectly hide a valid value of 0 */}
{price && <p>Price: {price}</p>}

Use an explicit check instead:

{price !== undefined && (
    <p>Price: {price}</p>
)}

11. Best Practices

  • Make only genuinely optional properties optional.
  • Use ? to indicate optional properties.
  • Use string | null when null is a valid value.
  • Provide default values for optional props when appropriate.
  • Use conditional rendering for optional content.
  • Use ReactNode for optional children, footer, and other renderable content.
  • Use React HTML attribute types when creating reusable HTML controls.
  • Use TypeScript utility types such as Partial, Required, Pick, and Omit when appropriate.
  • Keep component APIs simple and predictable.
  • Do not make required props optional just to avoid TypeScript errors.

12. Interview Questions and Answers

Q1. What are optional props in React TypeScript?

Optional props are properties that a parent component does not have to provide. We define them using the question mark symbol.

type Props = {
    name: string;
    age?: number;
};

Q2. What is the difference between optional and required props?

Required props must be supplied by the parent component. Optional props can be omitted.

Q3. How do you provide default values for optional props?

We can use default values in destructured function parameters.

function Button({
    size = "medium"
}: {
    size?: string;
}) {
    return <button>{size}</button>;
}

Q4. What is the difference between name?: string and name: string | null?

name?: string allows the property to be omitted. name: string | null requires the property but allows its value to be null.

Q5. What is Partial in TypeScript?

Partial makes all properties of an existing type optional.

Q6. What is ReactNode?

ReactNode is a React type that represents content React can render, including elements, strings, numbers, and other supported renderable values.

Q7. Can we combine optional custom props with HTML attributes?

Yes. We can use intersection types with React types such as InputHTMLAttributes to inherit standard HTML properties and add our own optional properties.

Q8. Does a default value make a prop optional?

No. The question mark in the type definition makes the prop optional. The default value only determines what the component uses when the prop is undefined.

13. Key Takeaways

  • Use ? to define optional props.
  • Required props must be supplied by the parent component.
  • Use default values when optional props need fallback values.
  • Understand the difference between optional, nullable, and undefined values.
  • Use conditional rendering to display optional content.
  • Use ReactNode for optional renderable content.
  • Use utility types such as Partial, Required, Pick, and Omit to reuse existing types.
  • Keep component props simple and type-safe.

Remember: Optional props make React components flexible, while TypeScript ensures that required properties and supplied values follow the expected types.

🔙
How to Create Type-Safe Reusable Form Components :👈 👉:How to Avoid any in React Applications

Comments and Discussion