TypeScript: Interfaces and Type Aliases
1. Interface
An interface is the most common way to define the structure of an object.
interface User {
readonly id: number; // Read-only
name: string;
age?: number; // Optional property
}
const user1: User = { id: 1, name: "John" };
2. Type Alias
A type alias assigns a new name to a type, making it easier to reuse. It is particularly useful when dealing with complex union types.
type ID = string | number;
type Point = { x: number; y: number };
const myId: ID = 123;
3. Interface vs Type
While both can be used in most situations, there are a few key differences:
| Feature | Interface | Type |
|---|---|---|
| Extensibility | Inheritance via extends | Uses & (Intersection) |
| Declaration Merging | Automatically merged when redefined | Not possible (causes an error) |
| Primary Use Case | Defining the structure of objects | All types including unions and primitives |
4. Defining Function Types
You can define the parameter and return types of a function using an interface or a type alias.
interface MathFunc {
(x: number, y: number): number;
}
const add: MathFunc = (a, b) => a + b;