Lesson 5 of 11 · 9 min

Union types and narrowing

A union type means "one of these types", written with |:

let id: string | number;
id = 42;        // fine
id = "A-42";    // fine
id = true;      // error

With a union, TypeScript only lets you do what is safe for every member:

function show(id: string | number) {
  return id.toUpperCase();
  // error: toUpperCase does not exist on type 'number'
}

Narrowing

When you check the type, TypeScript narrows it inside that branch:

function show(id: string | number): string {
  if (typeof id === "number") {
    return id.toFixed(0);       // here id is a number
  }
  return id.toUpperCase();      // here id must be a string
}

Ways to narrow:

Check Narrows to
typeof x === "string" string (also "number", "boolean")
Array.isArray(x) an array
x === null, x !== undefined removes null / undefined
if (x) removes null, undefined, and other "empty" values

null and undefined

With strict checking (used here), null is its own type. A value that might be missing is written string | null, and TypeScript makes you handle the missing case before using it.

Your task

  1. normalizeId(id: string | number): string: numbers become 6 digits with leading zeros (42 gives "000042"); strings are trimmed and upper-cased.
  2. countItems(x: string | string[] | null): number: null is 0, a list is its length, a single string is 1.
main.ts
function normalizeId(id: string | number): string {
  return id.trim().toUpperCase();
}

function countItems(x: string | string[] | null): number {
  return x.length;
}

console.log(normalizeId(7), countItems(["a", "b"]));

TypeScript 5.9 runs right here in your browser. The first run downloads about 1.5 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…