Loading Depth Study
Preparing your workspace
Type narrowing reduces a broad type into a more specific type using conditions and type guards.
A variable may have a union type such as string or number. Before using methods or operations that belong to only one type, TypeScript needs evidence about which type is currently present. Conditions such as typeof checks, equality checks, in checks, and custom type guards can provide that evidence. Narrowing makes code safer because TypeScript verifies that the operation is valid for the current type.
An API may return either a successful result containing data or an error object. Narrowing helps the application handle the two cases safely.
function formatValue(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}
console.log(formatValue("hello"));
console.log(formatValue(25));The string is converted to uppercase and the number is formatted with two decimal places.