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

Tuple Inference vs Array Inference

When TypeScript infers fixed-length tuples versus variable-length arrays from literals.

Tuple Inference vs Array Inference

What you'll learn: How TypeScript decides whether your literal is a fixed-length tuple or a variable-length array.

The Core Difference

When you write const arr = [1, 2, 3], TypeScript must choose: is this a tuple with exactly 3 elements of specific types, or a general array that can hold any number of number values?

By default, TypeScript infers arrays (variable-length) from literals, not tuples. This means [1, 2, 3] becomes number[], not [number, number, number].

Why Arrays Win by Default

Think of it like this: when you make a shopping list, do you usually mean "exactly these 3 items, no more, no less" or "items like these, maybe more later"? TypeScript assumes the flexible interpretation—you'll probably push or pop items.

const scores = [10, 20, 30];  // Inferred as number[]
scores.push(40);              // Allowed: arrays can grow

Forcing Tuple Inference

If you need a fixed-length tuple, you must be explicit with a type annotation or use as const:

const tuple: [number, number, number] = [10, 20, 30];
// tuple.push(40) would still work due to Array methods

const strictTuple = [10, 20, 30] as const;
// Inferred as readonly [10, 20, 30] - fixed length AND values

The Takeaway

Key Takeaway: TypeScript infers array literals as variable-length arrays (T[]) by default, not tuples. Use explicit type annotations or as const to force tuple inference when you need fixed-length behavior.