Advertisement
Advanced TypeScript, Primitive Types, Arrays & Tuples

How does TypeScript infer a tuple type versus a regular array type from an array literal, and how do 'as const' assertions change this?

Short answer

By default, an array literal like `[1, 2]` is inferred as the wider `number[]` array type, NOT a tuple — to get a precise, fixed-length tuple type inferred automatically, apply `as const`, which locks both the literal element values AND the tuple's fixed length/readonly-ness.

Save TypeScript mock interview
Advertisement
AModel answer
By default, an array literal like `[1, 2]` is inferred as the wider `number[]` array type, NOT a tuple — to get a precise, fixed-length tuple type inferred automatically, apply `as const`, which locks both the literal element values AND the tuple's fixed length/readonly-ness.
const loose = [1, 2];              // inferred as number[]
const tuple = [1, 2] as const;     // inferred as readonly [1, 2] -- a precise tuple of literal values
Real-world example
Getting precise literal-value tuple types for things like fixed configuration arrays or coordinate constants, without a manual type annotation.
Likely follow-ups
  • Why does 'as const' also make the resulting tuple type readonly, and how would you get a mutable tuple with the same shape?
Related topics