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
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.