Type Inference Flow: Bottom-Up and Top-Down
What you'll learn: How TypeScript infers types in two complementary directions—upward from values and downward from expected contexts.
Two Directions of Type Inference
TypeScript doesn't just infer types in one direction. It uses bidirectional type inference, flowing information both upward from the values you write and downward from the contexts where those values are used.
Think of it like a conversation between two people meeting in the middle: one person starts from the ground floor (the actual values in your code) and walks upward, while another starts from the top floor (the expected types based on context) and walks downward. They meet somewhere in between to agree on the final type.
Bottom-Up Inference: From Values Upward
Bottom-up inference starts with the literal values or expressions you write and infers types moving upward through your code.
When you write const x = 42, TypeScript looks at the value 42 and infers upward that x has type number. When you return something from a function, TypeScript infers the return type by examining what you actually return.
This is the inference you've seen most often—TypeScript looking at what you wrote and determining what type it must be.
Top-Down Inference: From Context Downward
Top-down inference (also called contextual typing) starts with an expected type based on where a value is being used, then flows that type information downward into the expression.
When you assign a callback to a typed parameter, TypeScript knows what type the callback should be. It flows that information downward into your callback function, inferring parameter types without you annotating them.
This is how callbacks in array methods like map know their parameter types—the context tells TypeScript what to expect.
How They Work Together
TypeScript combines both directions simultaneously. It starts inferring from values upward while also using contextual information downward. The two flows meet and constrain each other, producing the final inferred type.
When you pass an object literal to a function expecting a specific shape, top-down flow provides the expected structure while bottom-up flow provides the actual values. When there's a mismatch, TypeScript can catch it precisely because both flows are active.
Why This Matters
Understanding bidirectional flow explains many inference behaviors: why callback parameters are automatically typed, why object literals get excess property checks, why sometimes inference "just works" and other times you need annotations.
The interplay between bottom-up and top-down inference is what makes TypeScript feel intelligent—it's not just looking at your code in isolation, but understanding both what you wrote and where you're using it.
Key Takeaway: TypeScript infers types bidirectionally—bottom-up from the values you write and top-down from the contexts where those values are used, meeting in the middle to determine the most precise type possible.