Type Aliases
Give any type a reusable name with the type keyword.
Syntax
type ID = string | number;A type alias creates a new name for a type using the type keyword. Unlike interfaces, aliases can name any type — objects, unions, primitives, tuples, and more.
When to use
- Use
interfacefor object shapes you might extend. - Use
typefor unions, tuples, and complex combinations.
Example
Loading editor…
Press Run to execute the code.
When to use it
- A codebase names its string-based ID type as UserId so refactoring the ID shape only requires one change.
- A utility module creates an alias for a complex callback signature so every consumer uses the same type name.
- A team aliases a repeated union type to Status and imports it across multiple files for consistency.
More examples
Alias a primitive type
Creates semantic aliases for number and string so function signatures communicate intent rather than raw types.
type UserId = number;
type UserName = string;
function getUser(id: UserId): UserName {
return `user-${id}`;
}
const id: UserId = 42;
console.log(getUser(id));Alias a union type
Aliases a string literal union so every function that deals with user status reuses the same named type.
type Status = 'pending' | 'active' | 'banned';
function setStatus(userId: number, status: Status): void {
console.log(`User ${userId} is now ${status}`);
}
setStatus(1, 'active');
setStatus(2, 'unknown'); // Error: not assignable to type 'Status'Alias a complex object type
Nests type aliases to build a composed Route shape, avoiding repetition of the Coordinate object type.
type Coordinate = { lat: number; lng: number };
type Route = { origin: Coordinate; destination: Coordinate; distance: number };
function formatRoute(route: Route): string {
return `${route.origin.lat},${route.origin.lng} -> ${route.destination.lat},${route.destination.lng}`;
}
Discussion