×

typescript · level 2 · unit 2 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A lets a value be one of several types.

Sometimes a value can be one type or another. A locker might be numbered 12 or named "A3". A union type lists the choices with | between them, read as or: string | number.

You have met one already. prompt gives back string | null: a string, or nothing at all. That is why you needed ?? to get a plain string out.

The box may hold any type in the union, and nothing else. Try to put true in a string | number box and the checker says TS2322.

let locker: string | number = 12;
console.log(`Locker ${locker}`);
locker = "A3";
console.log(`Locker ${locker}`);
type Id = string | number;
const ids: Id[] = [7, "B2", 15];
console.log(ids);

A type alias is a handy way to name a union you use often, like type Id = string | number;.