Best Common Type Algorithm
You'll learn: How TypeScript automatically finds the most specific shared type when you mix different values together.
The Core Problem
When TypeScript infers types from arrays or expressions containing multiple values of different types, it needs to decide: "What single type can represent all of these values?" This is where the Best Common Type algorithm kicks in.
Think of it like finding a category that fits multiple items. If you have apples, oranges, and bananas, the best common category is "fruit," not "food" (too broad) or "apple" (too narrow).
How It Works
TypeScript examines all the values in an expression and looks for the most specific type that can accommodate every single one. It doesn't just pick any or give up — it tries to find the tightest fit.
// TypeScript infers: (string | number)[]
const mixed = [1, "hello", 2, "world"];
// TypeScript infers: (boolean | number)[]
const flags = [true, false, 42];
// TypeScript infers: number[]
const numbers = [1, 2, 3];
In the first example, TypeScript sees both number and string values. The best common type that includes both is the union type number | string.
The Algorithm's Choice
The algorithm picks the union of all unique types it encounters. It won't widen unnecessarily to something vague like any, but it also won't pick just one type and reject the others.
// TypeScript infers: (string | null)[]
const nullable = ["text", null, "more"];
Here, the best common type is string | null — not just string (which wouldn't include null) and not any (which would be too loose).
Key Takeaway: The Best Common Type algorithm finds the most specific union type that safely represents all values in an expression, keeping your types precise without being overly restrictive.