TypeScript · Narrowing and unions

typeof guard

Narrows primitives at runtime. TypeScript understands the guard in the same scope.

Syntax
if (typeof value === "string")

Example

Example
function pad(value: string | number) {
  if (typeof value === "number") return String(value).padStart(2, "0");
  return value;
}
console.log(pad(7));

More in this group

Assertion function Discriminated union Exhaustive switch in operator instanceof guard Non-null assertion Type assertion Type predicate

Learn this in the course

Reference pages are the quick answer. The course explains the why, shows the full example and ends with a challenge.

Open the course