Narrowing
Narrowing is proving which branch you are in, and there is no special syntax for it. Ordinary JavaScript checks do the work, and the compiler follows along.
typeof for primitives. === null for null. in for whether a property exists. Array.isArray. instanceof. A truthiness check. All of them narrow.
An early return narrows everything after it, which is why guard clauses read so well in TypeScript. Handle the awkward cases first, return, and the rest of the function is working with a known type.
Truthiness narrowing has a trap. if (s) excludes null, undefined and the empty string. For a string | null, that is usually fine and occasionally the bug: a legitimately empty string takes the wrong branch.
Mark this lesson complete
Signed in, your progress follows you to every device.