How do narrowing and type guards work?
Try code in the playgroundUnderstand the concept
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.
Important ideas
-
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".
Work through the 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.
Can you explain it without the notes?
How do narrowing and type guards work?
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
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.
Turn this concept into a clear answer.
- A type assertion asks the compiler to trust you; a type guard supplies a check that can protect the running program.
Keep connecting the ideas.
Next lesson: What are mapped types, conditional types and decorators?Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “How do narrowing and type guards work?”. Examples are study fragments; framework behavior can depend on your version.