Want a faster signal before interviews? Take the Interview Ready Check →

DAY 6 OF 30

Type aliases

Yesterday, in one sentence

What does ? do to a property in an object type, and what does readonly do?

Interview question

What does const stop from being reassigned, and what does readonly stop from being reassigned?

A type alias gives a name to a type. You can think of it as creating a variable for a type. You write type, the name, an =, and the type itself.

type User = {
  id: number;
  name: string;
};

let admin: User = { id: 1, name: "Xavier" };
let guest: User = { id: 2, name: "Beast" };

The type alias shape is defined once and referred to by name. Without a type alias you would write the whole object typeObject Type out at every place you use it. This makes type aliases reusable.

A type alias can name any type, and one alias can be used inside another.

type Id = string | number; // union type
type Scores = number[]; // array type, numbers only
type Position = [number, number]; // tuple type

type Player = {
  // type alias
  readonly id: Id; // readonly, cannot be reassigned
  name: string;
  nickname?: string; // optional property
  scores: Scores;
  position: Position;
};

const player: Player = {
  id: "p1",
  name: "Scott",
  scores: [90, 85],
  position: [0, 4],
};

Player uses everything from the last few days. id is a union typeUnion Type that cannot be reassigned, nickname is an optional property, scores is an array typeArray Type, and position is a tuple typeTuple.

Check yourself

Which of these is a valid type alias?
What is a type alias in TypeScript?