Type Narrowing
Narrow with typeof
After a typeof check, TypeScript treats the value as that type inside the branch.
function padLeft(value: string | number) {
if (typeof value === "number") {
return " ".repeat(value);
}
return value;
}
console.log(padLeft(3) + "hi");
Narrow null with equality
Check for null or undefined before reading properties.
function lengthOf(text: string | null): number {
if (text === null) {
return 0;
}
return text.length;
}
Narrow objects with in
The in operator checks for a property and narrows custom unions.
type Success = { ok: true; data: string };
type Failure = { ok: false; error: string };
function message(result: Success | Failure) {
if (result.ok) {
return result.data;
}
return result.error;
}
Keep narrowing honest
- Write real runtime checks; types erase at compile time
- Use
elsebranches so every case is handled - Prefer early returns for simple guards
- Discriminated unions with a shared tag field scale well
Comments
One comment per signed-in account. Comments are saved with this page’s URL.