Type Aliases

Give any type a reusable name with the type keyword.

Syntaxtype 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 interface for object shapes you might extend.
  • Use type for unions, tuples, and complex combinations.

Example

Try it yourself
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.

Example · ts
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.

Example · ts
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.

Example · ts
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

  • Be the first to comment on this lesson.