Skip to the workspace
Pebellslearn by building
Combining Types  ›  Lesson

Type Aliases

Type Aliases 12 minThe type keyword gives a name to any type, so you can write a long or repeated type once and reuse it by name.

typescript / Type Aliases

Explore each scene at your own pace.

01 · The rule

The rule

Type Aliases

The type keyword gives a name to any type, so you can write a long or repeated type once and reuse it by name.

Name a reusable type and follow that contract through several call sites.

By now the task tracker's types are getting long: "todo" | "doing" | "done" in five functions, the full task shape in three. Change a status and you must hunt down every copy. The fix is the keyword you have been quietly using all along: type.

The rule

type gives any type a name; the name is a nickname, not a new type.

A type alias names a type so you can refer to it:

type TaskId = number;
type Status = "todo" | "doing" | "done";
type Pair = [TaskId, string];
type Task = {
  id: TaskId;
  title: string;
  status: Status;
};
type TaskFilter = (task: Task) => boolean;

The right-hand side can be any type: a primitive, a union, a tuple, an object shape, a function type, or a combination. Aliases can refer to other aliases, which is how small names build up into a readable model. They can also take type parameters, like type Box<T> = { value: T }, a topic for a later course on generics.

The important subtlety: an alias does not create a separate type. It is just another name for the same thing.

type TaskId = number;
type UserId = number;

const t: TaskId = 5;
const u: UserId = t;   // allowed: both are just number

TypeScript will not stop you mixing up a TaskId and a UserId, because both are number. The alias adds readability, not protection.

Two more facts:

  • An alias cannot be declared twice with the same name in the same scope. (Interfaces behave differently here, as the last section shows.)
  • Aliases are erased when compiled, like every type.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.