Sub topic 1
Why Union Types Need Narrowing
Prerequisites
This chapter assumes that you know basic TypeScript syntax, functions, type aliases, and union types. You should also be familiar with if, switch, and the ternary operator. A union type uses | to describe a value that can have one of several types.
A union describes possibilities
Consider this function:
function formatValue(value: string | number): string {
return value.toUpperCase();
}The function does not compile. toUpperCase exists on string, but not on number. The declared type string | number means that callers may pass either type. TypeScript must check the function against both possibilities.
A union gives you access only to operations that are safe for every member of the union. For example, you can compare value with another value or convert it to a string, but you cannot call a string-only method until you have proved that the value is a string.
Narrowing is the process of replacing a wider type with a more specific type after a check. The check provides evidence that one or more possibilities no longer apply.
Control flow provides the evidence
TypeScript follows the paths through your code. When a condition proves something about a value, TypeScript updates the value's type inside that path.
function formatValue(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}At the start, value has type string | number. Inside the if block, the typeof check proves that it is a string. After the block, the function has already returned when the value was a string. Therefore, the remaining path can treat value as a number.
This analysis is called control flow analysis. It considers conditions, early returns, thrown errors, and assignments when deciding which types are still possible.
Narrow only what the check proves
A narrowing check must match the type information you need. Checking whether a value exists does not prove that it has a particular object shape.
type Result = string | { message: string };
function describe(result: Result): string {
if (typeof result === "string") {
return result;
}
return result.message;
}The typeof check separates the primitive string member from the object member. In the second path, the only remaining union member is { message: string }, so the message property is safe to read.
A common mistake is to use a type assertion instead of a check:
function unsafeFormat(value: string | number): string {
return (value as string).toUpperCase();
}The assertion changes what the compiler believes, but it does not inspect the runtime value. If the caller passes a number, the program can fail. A narrowing check connects the type claim to an actual condition.
The benefit of narrowing
Union types let an API accept several related forms without using any. Narrowing keeps that flexibility while requiring each implementation path to handle values safely. The compiler can then detect missing checks when you add another union member or use an operation that belongs to only one member.
Use the smallest check that establishes the fact you need. Do not silence an error with an assertion when a runtime check can prove the value's type.
Exercise
Why does TypeScript reject value.toUpperCase() when value has type string | number, and what kind of change makes the call safe?
Show answer
The method exists only on string, so the union does not guarantee that it is available. Check the value, such as with typeof value === "string", and call the method inside the narrowed branch.