CodingNeed.

2 · Model and build · 8 MIN

Narrow a union

Arrays store values in order, starting at index zero.

A union allows one of several types. A null check narrows the value inside each branch. Handle absence explicitly so you never read length from null.

A row of numbered lockers starts at locker 0 in JavaScript.

Read the example

function length(value: string | null): number {
  if (value === null) return 0;
  return value.length;
}
console.log(length("Ada"));
Check the expected output
3

Your challenge

Return the length of the input string, or zero for null.

Common trap

The last index is length - 1, not length.

Next lesson: Keep a type relationship