Type Aliases in TypeScript
Type Aliases in TypeScript
Section titled “Type Aliases in TypeScript”What are Type Aliases?
Section titled “What are Type Aliases?”A type alias creates a new name for a type. Unlike interfaces, type aliases can represent any type — not just objects.
Basic Type Alias
Section titled “Basic Type Alias”// Object typetype User = { id: number; name: string; email: string;};
// Primitive aliastype UserId = string;type Age = number;
// Union typetype Status = "active" | "inactive" | "pending";
// Function typetype Callback = (error: Error | null, result?: unknown) => void;
// Tuple typetype Pair = [string, number];Type Alias Usage
Section titled “Type Alias Usage”// Union types (not possible with interfaces)type Result<T> = { success: true; data: T } | { success: false; error: string };
// Mapped typestype Readonly<T> = { readonly [K in keyof T]: T[K] };
// Conditional typestype IsString<T> = T extends string ? true : false;
// Template literal typestype EventName = `on${Capitalize<string>}`;Differences from Interfaces
Section titled “Differences from Interfaces”| Feature | Type Alias | Interface |
|---|---|---|
| Object shapes | ✅ | ✅ |
| Union types | ✅ | ❌ |
| Intersection types | ✅ (&) | ✅ (extends) |
| Declaration merging | ❌ | ✅ |
| Computed properties | ✅ | ❌ |
| Mapped types | ✅ | ❌ |
| Extends classes | ❌ | ✅ |
Real Project Example
Section titled “Real Project Example”// API response with discriminated uniontype ApiResponse<T> = { success: true; data: T; pagination?: { page: number; total: number };} | { success: false; error: { code: string; message: string };};
// Utility typestype DeepPartial<T> = { [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];};Interview Questions
Section titled “Interview Questions”Easy: What is a type alias?
Medium: Can type aliases represent union types? How?
Hard: Why can’t type aliases do declaration merging?