Common type inference
Concept and syntax
When an array contains different kinds of values, TypeScript may infer a union element type. [1, "tea"] is inferred as (string | number)[], an array whose elements can be numbers or strings. Parentheses mean the union applies to each element. The inferred union restricts writes but is not a fixed positional record. A homogeneous array such as [1, 2] instead has numeric elements.
Working example
Compile standalone examples in a fresh directory with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
const values = [1, "tea"];values.push(2, "coffee");const numbers = [1, 2];console.log(values.length, numbers.length);Expected output (one line per log):
4 2Common mistake
Intentionally invalid; check this snippet separately. Do not run it.
Expected compiler diagnostic: TS2345. Neither string nor number includes true. Add boolean to the intended element type only if the design requires it.
Practice and recap
Start with [1, "tea"], add another numeric value and then try adding false. Predict the inferred element union.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Common type inference — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
Which element type is inferred from [1, "tea"]?
Does the inferred array require a string at index 1 forever?
Which value could be pushed into values without changing its inferred type?
const values = [1, "tea"];values.push(true);