Sub topic 1
TypeScript Type Narrowing and Type Guards
Prerequisites
Assume you know basic TypeScript syntax, functions, type aliases, union types such as string | number, and JavaScript control flow with if, switch, and ternary expressions.
Why Union Types Need Narrowing
A union type says that a value can have one of several types. For example:
function format(value: string | number): string {
return value.toUpperCase();
}This fails because toUpperCase exists on string, but not on number. TypeScript only allows operations that are valid for every member of the union.
Narrowing means checking which type a value has, then using that information in a branch. The check makes the value’s type more specific.
How Control Flow Analysis Narrows Types
TypeScript performs control flow analysis. It follows conditions, returns, and unreachable branches to update a variable’s type.
function format(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}Inside the if block, value is a string. After the early return, the remaining possibility is number.
Narrowing with `typeof`
The typeof operator checks common JavaScript primitive categories:
"string""number""boolean""bigint""symbol""function""object""undefined"
Use it when union members differ by primitive type. Remember that typeof null is "object", so a null check may also be needed.
Truthiness Narrowing and Its Pitfalls
A truthiness check removes values that JavaScript treats as false, such as false, 0, "", null, and undefined.
function label(name: string | null): string {
if (name) {
return name.toUpperCase();
}
return "Unknown";
}This is safe when an empty string should count as missing. However, truthiness can reject valid values such as 0 or "". Use an explicit comparison when those values matter.
Exercise
In format(value: string | number), which check lets the true branch call string methods?
Show answer
typeof value === "string"