Course contentsShow
← TypeScript
Lesson 1372 of 1,79632. Advanced PatternsFree lesson

Tuple Type Inference from Literals

How TypeScript infers tuple types from array literals and when it widens to arrays instead.

Tuple Type Inference from Literals

You'll learn: How TypeScript decides whether to infer a tuple type or a regular array type from your literal syntax.

The Inference Choice

When you write an array literal like [1, "hello", true], TypeScript faces a decision: should this be typed as a tuple [number, string, boolean] (preserving exact position and type) or as an array (number | string | boolean)[] (allowing any length and order)?

By default, TypeScript infers arrays, not tuples, from most literals. This is because arrays are more flexible and commonly needed. The type system assumes you want something mutable that can grow or shrink.

When TypeScript Infers Arrays

const coords = [10, 20];
// Type: number[]
// Not: [number, number]

Here, coords is typed as number[], meaning you could push more numbers onto it or remove elements. TypeScript doesn't assume you want exactly two elements.

const mixed = [1, "text", true];
// Type: (number | string | boolean)[]

Again, an array type—not [number, string, boolean].

Forcing Tuple Inference with Type Annotations

If you want a tuple, you must tell TypeScript explicitly:

const coords: [number, number] = [10, 20];
// Now it's a tuple

const mixed: [number, string, boolean] = [1, "text", true];
// Exact positions enforced

Using as const for Tuple Inference

The as const assertion makes TypeScript infer the narrowest possible type, which includes treating arrays as readonly tuples:

const coords = [10, 20] as const;
// Type: readonly [10, 20]
// Not number[], but a readonly tuple of literal types

This gives you a tuple with literal types at each position, and makes it immutable.

The Widening Rule

Without explicit typing or as const, literals widen:

  • [1, 2] → number[] (widens to array)
  • [1, 2] as const → readonly [1, 2] (stays as tuple of literals)

Key Takeaway: TypeScript defaults to array types from literals for flexibility; use explicit type annotations or as const to get tuple types instead.