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

Using as const for Tuple Inference

Forcing readonly tuple inference with as const to preserve exact structure.

Using as const for Tuple Inference

What you'll learn: How to use as const to force TypeScript to infer exact tuple types instead of widening to general arrays.

The Core Problem

When you create an array literal in TypeScript, the compiler usually infers it as a mutable array type rather than a precise tuple. This means TypeScript assumes you might add or remove elements, so it widens the type to allow flexibility:

const pair = [1, 'hello'];
// Type: (number | string)[]
// Not: [number, string]

Notice how TypeScript inferred (number | string)[] — a general array that could have any length and any mix of numbers and strings. The exact structure [number, string] is lost.

The Solution: as const

The as const assertion tells TypeScript: "This value is deeply readonly and should preserve its exact structure." For arrays, this forces tuple inference:

const pair = [1, 'hello'] as const;
// Type: readonly [1, 'hello']

Now TypeScript knows this is exactly a two-element tuple with a number literal 1 at index 0 and string literal 'hello' at index 1. No widening occurs.

Why This Matters

Without as const, functions expecting tuples won't accept your array:

function getCoordinates() {
  return [10, 20]; // Type: number[]
}

function plot(point: [number, number]) {
  // ...
}

plot(getCoordinates()); // Error: number[] not assignable to [number, number]

With as const, the exact structure is preserved:

function getCoordinates() {
  return [10, 20] as const;
  // Type: readonly [10, 20]
}

// Works! (readonly tuples are assignable to mutable ones)

Key Takeaway: Use as const when you need TypeScript to infer an array literal as a readonly tuple with exact types, preserving the precise structure instead of widening to a general array type.