Sub topic 2
How TypeScript Infers Array Literal Types
This chapter assumes you know basic JavaScript arrays and array methods, basic TypeScript type annotations, and union types. It covers what type TypeScript gives an array literal when you write no annotation, and how to change that result when it is not what you want.
The basic rule: an array of the union of its elements
When you write an array literal without an annotation, TypeScript looks at the type of each element. It then builds one element type that covers all of them and gives the variable an array of that type.
const inferred = [1, 2, 3]; // number[]
const inferredMixed = [1, "a"]; // (string | number)[]
const flags = [true, false]; // boolean[]Three things are worth noticing.
- The element type is a union when the elements differ.
[1, "a"]becomes(string | number)[], not a tuple. - The parentheses matter.
(string | number)[]is an array whose elements may each be a string or a number.string | number[]would mean "a string, or an array of numbers". - The inferred type is an array type, so it has no fixed length. TypeScript does not remember that the literal had two elements.
The union is not always written in the order you typed the elements. TypeScript normalizes unions, so do not rely on the display order.
Literal types are widened
Each element in [1, 2, 3] has the literal type 1, 2 or 3. If the variable kept those literal types, you could not assign another number to an element. TypeScript therefore widens them to number.
const nums = [1, 2, 3];
nums[0] = 42; // allowed: nums is number[]
const letters = ["a", "b"];
letters.push("c"); // allowed: letters is string[]Widening happens even though nums is declared with const. The const keyword stops you from reassigning the variable. It does not make the elements immutable, and it does not change the inferred element type. This is the same behavior JavaScript has at runtime, and TypeScript's types follow it.
You can see the difference by comparing a plain const primitive with an array.
const n = 1; // type is the literal 1
const arr = [1]; // type is number[], not 1[]Mixed elements and object elements
For objects, TypeScript infers a union of the object shapes, and it normalizes them so that missing properties become optional undefined properties.
const items = [
{ id: 1, name: "pen" },
{ id: 2 },
];
// { id: number; name: string }[] | { id: number; name?: undefined }[]
// In practice the element type is { id: number; name: string } | { id: number; name?: undefined }This normalization lets you read item.name on every element without an error, and the value is string | undefined. It is helpful for data of uneven shape, but it can surprise you if you expected an error for the missing property.
The empty array literal
An empty literal has no elements to look at. What TypeScript does depends on your compiler settings and on where the array is used.
With strict enabled (specifically noImplicitAny), a let or const initialized to [] gets an evolving array type. TypeScript tracks what you push into it and refines the type as the code flows.
const evolving = [];
evolving.push(1);
evolving.push("a");
const value = evolving[0]; // string | numberThe evolving type only works for local variables whose type TypeScript can follow. If the array escapes into a closure or is read before any push, you may get an implicit any error, such as "Variable 'evolving' implicitly has type 'any[]' in some locations where its type cannot be determined."
Outside strict mode, [] is inferred as any[], and in some positions as never[]. Because both are confusing, annotate empty arrays whenever they are not trivially local.
const ids: number[] = [];
ids.push(1);
// ids.push("a"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.Contextual typing: the annotation wins
Inference runs in both directions. If a type is already expected at that position, TypeScript uses it to type the literal. This is called contextual typing. The expected type can come from a variable annotation, a parameter type, or a return type.
const scores: number[] = [90, 85, 72];
const maybe: (string | null)[] = ["a", null];
function total(nums: number[]): number {
return nums.reduce((sum, n) => sum + n, 0);
}
total([1, 2, 3]); // the literal is checked against number[]Contextual typing also flows into callbacks inside the literal. This matters when the context is a union of literal types.
type Direction = "up" | "down";
const moves: Direction[] = ["up", "down", "up"]; // fine
const looseMoves = ["up", "down"]; // string[]
// const bad: Direction[] = looseMoves;
// Error: Type 'string[]' is not assignable to type 'Direction[]'.The literal written directly against Direction[] keeps its literal types because the annotation tells TypeScript to. The same literal assigned to an unannotated variable widens to string[], and then it no longer fits Direction[]. This is one of the most common inference surprises. The fix is either to annotate the variable or to use as const, covered next.
Arrays versus tuples: inference never guesses a tuple
A literal like [1, "a"] looks like a pair, but TypeScript infers (string | number)[]. It does not guess that you meant a tuple. The reason is that arrays are far more common in JavaScript code, and treating every short literal as a fixed-length tuple would break ordinary code such as nums.push(4).
You get a tuple only when something asks for one. There are two ways to ask.
const pair = [1, "a"]; // (string | number)[]
const fixed = [1, "a"] as const; // readonly [1, "a"]
const typed: [number, string] = [1, "a"]; // [number, string]The difference between the last two lines is important:
as constfreezes the type. The result isreadonly [1, "a"]. The elements keep their literal types, and the array becomes read only.- An annotation like
[number, string]gives a mutable tuple with widened element types.
Use as const when you want the exact literal values preserved. Use an annotation when you want a particular tuple shape that you can still modify.
Returning a tuple from a function
Return type inference follows the same rule. A function that returns an array literal returns an array type, even if you meant a pair.
function minMaxInferred(nums: number[]) {
return [Math.min(...nums), Math.max(...nums)];
}
// return type: number[]
function minMax(nums: number[]): [number, number] {
return [Math.min(...nums), Math.max(...nums)];
}
// return type: [number, number]
const [lo, hi] = minMax([3, 1, 4, 1, 5]); // lo: number, hi: numberWith the inferred version, destructuring still works, but the type does not record that exactly two numbers come back. Annotating the return type is the reliable way to get a tuple.
Inference with `as const` in detail
as const is a const assertion. It changes how the literal is typed in three ways:
- Array literals become readonly tuples.
- Primitive elements keep their literal types instead of widening.
- Object literals inside get
readonlyproperties.
const config = {
levels: ["low", "high"],
limits: [10, 20],
} as const;
// levels: readonly ["low", "high"]
// limits: readonly [10, 20]
type Level = (typeof config.levels)[number]; // "low" | "high"The last line is a common pattern. Indexing a readonly tuple type with number produces the union of its element types, so one list of values can drive both runtime code and a type.
A const assertion applies only to literal expressions. You cannot write someVariable as const, because there is no literal to freeze.
Best common type and subtype reduction
When elements are related by subtyping, TypeScript may keep the union as written or reduce it. For example, an array containing a Dog and an Animal where Dog extends Animal can be inferred as Animal[] in some situations, because Dog is a subtype and the union collapses.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {}
}
const pets = [new Animal(), new Dog()]; // Animal[]
// pets[1].bark(); // Error: Property 'bark' does not exist on type 'Animal'.The consequence is that the extra members of the subtype are not visible through the array. If you need them, annotate a union such as (Animal | Dog)[] and narrow before using bark, or restructure the data so the array holds a single discriminated type.
Spread and inference
Spreading arrays into a literal also produces an array of the combined element types.
const a = [1, 2];
const b = ["x", "y"];
const both = [...a, ...b]; // (string | number)[]If you spread tuples into a literal, the result is still an array unless the context asks for a tuple. Chapter material on variadic tuple types later in this tutorial shows how to preserve exact tuple types through generic functions.
Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| `string[]` is not assignable to a union-of-literals array | Unannotated literal widened to `string[]` | Annotate the variable or use `as const` |
| Destructured pair has type `number` for both, with no length check | Function return was inferred as an array | Annotate the return type as a tuple |
| `any[]` or implicit `any` error on `[]` | Empty literal with nothing to infer from | Annotate, for example `const xs: number[] = []` |
| Subtype members missing on elements | Union collapsed to the base type | Annotate a wider union and narrow |
| Cannot push to an array | `as const` made it a readonly tuple | Use an annotation instead of `as const` |
How the pieces fit together
Exercises
Exercise
What type does TypeScript infer for const xs = [1, "a", true];, and why is it not a tuple?
Show answer
(string | number | boolean)[]. TypeScript infers an array of the union of the element types, and it only produces a tuple when you ask for one with an annotation or as const.
Exercise
The code below fails to compile. Give two different fixes. type Mode = "r" | "w"; const modes = ["r", "w"]; const allowed: Mode[] = modes;
Show answer
The variable modes is widened to string[], which is not assignable to Mode[]. Fix 1: annotate it, const modes: Mode[] = ["r", "w"];. Fix 2: use a const assertion, const modes = ["r", "w"] as const; and change the target type to readonly Mode[], because a readonly tuple is not assignable to a mutable array type.
Exercise
A function function pair() { return [1, "a"]; } returns what type? How do you make it return [number, string]?
Show answer
It returns (string | number)[]. Annotate the return type: function pair(): [number, string] { return [1, "a"]; }.