Contextual Union Types
You'll learn: How TypeScript automatically narrows inferred types when the expected type is a union.
The Core Idea
When TypeScript knows you're trying to produce a value that must match a union type, it uses that knowledge to narrow what it infers from your code. Instead of inferring a broad type, it picks the most specific matching member from the union.
Think of it like ordering from a limited menu. If the restaurant only serves pizza, pasta, or salad, and you say "I want something with tomato sauce," the server immediately knows you mean pizza or pasta—not some random dish. TypeScript does the same: it sees the allowed options (the union) and infers only what fits.
How It Works in Practice
When you assign a value to a union-typed variable or pass an argument to a union-typed parameter, TypeScript checks which union member your value matches. It won't just infer string if the union expects "red" | "blue"—it'll infer the literal type that matches.
type Color = "red" | "blue" | "green";
let favoriteColor: Color;
// TypeScript infers "red" (literal), not string
favoriteColor = "red";
// This context also applies to function parameters
function setColor(c: Color) {}
// "blue" is inferred as the literal "blue"
setColor("blue");
Without the Color union context, TypeScript would infer "red" as type string. But because the expected type is the union Color, it narrows to the matching literal.
Key Takeaway: When assigning to a union type, TypeScript narrows its inference to match specific union members automatically, giving you precision without extra annotations.