Lesson 3 of 10

Union types and narrowing

Goal

A value with more than one type

01

Explanation

A product ID might arrive as a number like 42 one time and as a string like "ab12" the next. The type string | number says exactly that: the value is one of the two types. This is called a union.

The compiler only lets you do what both types have in common, so id.toUpperCase() is a type error, because numbers have no toUpperCase. It's the same mistake that crashes a JavaScript program the moment a number reaches the function.

The fix is narrowing: inside if (typeof id === "number") the compiler knows id is a number, and in the other branch it knows it's a string. Keep in mind that typeof can't tell an array, null and an object apart, because they're all "object".

02

Your task

Give the parameter of formatId the type string | number and make it return a string. A string comes back in uppercase after a #, like "#AB12", and a number is padded with zeros to four digits, like "#0042".

Checks

5 checks
  1. No type errors
  2. formatId accepts a string and a number
  3. formatId rejects any other type
  4. formatId("ab12") returns "#AB12" for a string
  5. formatId(42) returns "#0042" for a number
main.ts
OutputTypeScript 5.9

Loading the TypeScript compiler. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.