Types and Interfaces
What are Types and Interfaces?
Types and interfaces both let you describe the shape of an object.
In React, we often use them for declaring props, state, API responses, and config objects.
// Using type
type User = {
id: string;
name: string;
age?: number; // optional
};
// Using interface
interface Product {
id: number;
title: string;
}When to Use What?
Interface
Use interface when you're working with object-like structures such as props and API response types.
Interfaces can be extended using extends , making it easy to reuse and compose types in a clean, modular way.
💡 React Tip: Prefer
interfacefor component props because they’re extendable.
Type
Use type for unions, primitives, or when combining complex types.
Union Types
Discriminated Unions (Tagged Unions)
Useful for modeling variants like UI components and API states.
Function Types
This is often used in props like onClick, onSubmit, or custom event handlers in React components.
Tuple Types
Tuples are great because they allow each element in the array to be a known type of value.
Mapped Types with type
Combining Types with & (Intersection)
Last updated