TypeScript by Example

Type Aliases

Naming primitive, object, union, and intersection shapes with the type keyword.

A type alias gives a name to a type expression. Use aliases when the domain already has a name for the value or shape.

Simple aliases make signatures speak the domain instead of exposing raw primitives everywhere.

type UserId = string;
type RetryCount = number;
 
function loadUser(id: UserId, retries: RetryCount) {
  return { id, retries };
}

Aliases can name object shapes, unions, and intersections.

type Point = { x: number; y: number };
type Status = "draft" | "published" | "archived";
type Timestamped = { createdAt: Date };
 
type TimestampedPoint = Point & Timestamped;
 
function canEdit(status: Status): boolean {
  return status === "draft";
}

In production

Type aliases are the natural way to name closed domain concepts: UserId, Status, ApiResponse<T>, or a set of allowed routes. When a union grows into several object cases, give it a discriminated union.

Enjoyed this? Get more software craft delivered to your inbox.