How do narrowing and type guards work?
Practice this questionWANT TO UNDERSTAND THE CONCEPT FIRST?Learn How do narrowing and type guards work?
Definition:
Narrowing is TypeScript's process of reducing a broad type to a more specific type based on control flow and checks. A type guard is a check that gives the compiler evidence about a value, such as typeof, in or a custom predicate. Correct guards help application code safely use data that starts out uncertain.
Key points:
-
A check like
typeof value === 'string'narrows the type. -
A custom guard can return
value is Userafter checking required fields. -
A type assertion like
as Userdoes not validate anything. -
A custom predicate must really check the claimed shape; TypeScript trusts the predicate's return type.
-
Check for
nullbefore using object properties, because runtimetypeof nullis"object".
Example:
function display(value: unknown): string {
if (typeof value === 'string') return value.toUpperCase();
if (typeof value === 'number') return value.toFixed(2);
return 'Unsupported value';
}- The checks narrow
unknownbefore type-specific methods are used.
Interview point:
- A type assertion asks the compiler to trust you; a type guard supplies a check that can protect the running program.
Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “How do narrowing and type guards work?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.