Course contentsShow
← TypeScript
Lesson 174 of 1,7964. Type InferenceFree lesson

Best Common Type in Context

How contextual type hints help TypeScript choose better common types in arrays and conditionals.

Best Common Type in Context

You'll learn how contextual clues help TypeScript pick smarter, more specific types when combining values.

The Problem: Choosing Between Multiple Types

You've learned that TypeScript uses the Best Common Type algorithm to figure out array types and conditional expressions. But sometimes, TypeScript has extra information from context that helps it make better choices.

Think of it like choosing a gift: if you only know "they like books," you might pick any book. But if you also know "it's for their cookbook collection," you'll choose something more specific.

How Context Improves Type Selection

When TypeScript sees an array or conditional, it doesn't just look at the values you provided—it also checks if there's contextual type information from where you're using that value.

// Without context: TypeScript picks (number | null)[]
const numbers = [1, 2, null];

// With context: a function expects number[]
function processNumbers(nums: number[]) {
  // ...
}

// TypeScript knows you want number[], so it tries harder
// to treat this as number[] (and flags null as an error)
processNumbers([1, 2, null]); // Error: null not assignable

The context (the function parameter type number[]) guides inference. TypeScript doesn't just say "could be anything these values share"—it says "what type would make this work in this context?"

This works in conditionals too:

let value: string;
value = true ? "hello" : "world"; // Context expects string
// TypeScript infers "hello" | "world" (both strings)

Key Takeaway: Contextual type hints from function parameters, variable annotations, or return types help TypeScript infer more precise common types, catching errors earlier and providing better type safety.