Learn the concept
Interfaces vs Type Aliases
Both define object shapes, but interfaces can be extended and merged (declaration merging), while type aliases can represent unions, tuples, and primitives. Use interfaces for objects/classes and type aliases for unions or complex types.
Interfaces:
extendsType Aliases:
& to combineWhen to Use:
// Define object shape with interface
interface User {
id: number;
name: string;
email: string;
age?: number; // Optional property
readonly createdAt: Date; // Cannot be modified after creation
}
// Using the interface
const user: User = {
id: 1,
name: 'Alice',
email: 'alice@example.com',
createdAt: new Date()
};
user.createdAt = new Date(); // Error: Cannot assign to 'createdAt' because it is read-only
// Extending interfaces
interface Employee extends User {
department: string;
salary: number;
}
const employee: Employee = {
id: 1,
name: 'Bob',
email: 'bob@company.com',
createdAt: new Date(),
department: 'Engineering',
salary: 80000
};Defining React component props with interfaces for extendability and declaration merging
Using interfaces for service contracts that different implementations can satisfy
Using declaration merging to allow plugins to extend core type definitions
Define shape interfaces (Circle, Rectangle, Triangle) implementing a common Measurable interface
Build a theme type system using declaration merging to allow plugins to add custom theme properties