Interfaces and Type Aliases
Interfaces and type aliases define the shape of objects.
Interface: Defines an object type with named properties.
- Can be extended with 'extends'
- Can be implemented by classes
- Automatically merged (declaration merging)
Type Alias: Creates a new name for any type.
- More flexible - can alias primitives, unions, etc.
- Cannot be extended (use intersection instead)
- No declaration merging
When to Use:
- Interface: For object shapes, especially in public APIs
- Type: For unions, intersections, mapped types
Optional Properties: Use ? to make properties optional.
Readonly Properties: Use readonly to prevent modification.
Code Examples
Interfaces and Typestypescript
// Interface
interface User {
id: number;
name: string;
email?: string; // optional
readonly createdAt: Date; // cannot be modified
}
const user: User = {
id: 1,
name: "Alice",
createdAt: new Date()
};
// user.createdAt = new Date(); // Error! readonly
// Extending interfaces
interface Employee extends User {
department: string;
salary: number;
}
const employee: Employee = {
id: 2,
name: "Bob",
createdAt: new Date(),
department: "Engineering",
salary: 100000
};
// Type alias
type Point = {
x: number;
y: number;
};
type ID = string | number; // Union type
// Intersection type
type AdminUser = User & {
permissions: string[];
};
// Function type
type Callback = (data: string) => void;
// Generic interface
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
const response: ApiResponse<User[]> = {
data: [user],
status: 200,
message: "Success"
};
console.log(response.data[0].name);Interfaces and types are often interchangeable. Use interfaces for objects and classes, types for unions and complex types.
Quick Quiz
1. What does the ? after a property name mean?
Was this lesson helpful?