type narrowing
The compiler refining a broad type to a more specific one inside a block, after a check proves which case applies.
In more detail
Inside if (typeof x === "string"), x is a string. Narrowing comes from typeof, instanceof, the in operator, equality and truthiness checks, discriminant tags, type predicates and assertion functions. It is how you safely work with unions and unknown.
Related terms
- control flow analysis — The compiler following every branch, return and throw in your code to work out the narrowest type a variable can have at each line.
- type guard — A run time check, such as typeof x === "string" or a custom function, that the compiler uses to narrow a type.
- union type — A type that allows one of several listed types or values, written with a vertical bar, such as int | None in Python or "small" | "large" in TypeScript.
- unknown (type) — The type-safe type for a value that could be anything, which you must narrow before you can use it.
Taught in
- Type Annotations, Type Inference And Contextual Typing — Production TypeScript
- Literal Types: String, Number, Boolean Literals And const — Production TypeScript
- any Versus unknown: Defensive Typing In Practice — Production TypeScript
- never: The Bottom Type And Exhaustive Switch Checking — Production TypeScript
- Union Types, Intersections And Property Conflicts — Production TypeScript
- Discriminated Unions: Tagged Variants And Pattern Matching — Production TypeScript
- Tuples: Fixed Length, Labeled Elements And Variadic Tuples — Production TypeScript
- Typeof Guards, Truthiness And Equality Narrowing — Production TypeScript
- The in Operator And Instanceof Narrowing — Production TypeScript
- Custom Type Predicates: Functions Returning is Type — Production TypeScript
- Assertion Signatures: asserts condition And Invariants — Production TypeScript
- Exhaustive Narrowing With never In Production Handlers — Production TypeScript
- The Spine Artifact: Generating Typed Models From OpenAPI — Production TypeScript