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
};