Lesson 11 +10 XP

Type Aliases & Union Types

Type Aliases & Union Types

Type aliases allow naming any type definition, including primitives, unions, tuples, and functions.

Defining Type Aliases

Syntax: type AliasName = Type Definition;

type UserID = string | number;
type Point = { x: number; y: number };

let id: UserID = 101;
id = "usr_999"; // Valid due to Union type!

Union Types (|)

Unions allow a value to be one of several specified types.

function printID(id: string | number) {
  if (typeof id === "string") {
    console.log(id.toUpperCase()); // Narrowed to string
  } else {
    console.log(id.toFixed(2));     // Narrowed to number
  }
}

Type Aliases vs Interfaces

FeatureInterfaceType Alias
Object TypesSupportedSupported
Unions & PrimitivesNoSupported
Declaration MergingYesNo
Extends / Combinesextends& (Intersection)

TL;DR

  • Use type aliases to give custom names to primitive, union, tuple, or function types.
  • Union types (A | B) accept values matching type A OR type B.