Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 96 ยท Basic Types

Arrays and Tuples

Learn how TypeScript types arrays and tuples - T[] vs Array<T>, readonly arrays, fixed-length tuples, optional, rest and named elements, and readonly tuples.

Almost every program works with lists: a list of prices, a list of users, a list of lines read from a file. In JavaScript an array can hold anything, and nothing stops you from pushing a string into a list of numbers. TypeScript adds one simple promise: every element of a typed array has the same declared type, so methods like map, filter and reduce know exactly what they are working with.

Sometimes, though, a list isn't really a list. A pair like ['Ada', 36] or a coordinate like [52.52, 13.40] has a fixed length, and each position means something different. For those, TypeScript has tuples: arrays with a known length and a known type at every index.

This lesson covers both, plus the readonly versions that stop accidental changes. If you need a refresher on how arrays behave at runtime, see the JavaScript lesson on arrays. The types here build on Primitive Types.

Array types: T[] and Array<T>

There are two ways to write "an array of strings", and they mean exactly the same thing:

TypeScript
const tags: string[] = ['news', 'tech'];
const moreTags: Array<string> = ['sports'];

string[] is the short form and the one most codebases use. Array<string> is the generic form: Array is a type that takes another type as a parameter, a pattern you will master in Generics. Pick one style and use it consistently; many teams use T[] for simple element types and Array<...> when the element type is long.

Most of the time you don't need to write either, because TypeScript infers array types from the values:

TypeScript Inferred array types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Hover over the variables in a real editor and you'll see the types from the comments. mixed is the interesting one: when the elements have different types, TypeScript infers an array of a union type, (string | number)[]. Every element might be either, so you have to check which one you have before using type-specific methods. That check is called narrowing; Union Types and Narrowing cover it properly.

Mind the parentheses. (string | number)[] is an array whose elements are strings or numbers. string | number[] is either a single string or an array of numbers. They are very different types.

Empty arrays need a type

An empty array literal gives TypeScript nothing to infer from. Inside a function, TypeScript lets an empty array "evolve" as you push into it, but the clearest and safest habit is to annotate empty arrays that you fill later:

TypeScript
const errors: string[] = [];
errors.push('Name is required');

The element type is enforced

Once an array has a type, every write is checked. Pushing the wrong kind of value, or assigning a whole array of the wrong type, is a compile error. In our editor any type error stops the run, so the next example prints only the errors:

TypeScript Wrong element type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The compiler reports both problems, with the line and column of each:

TEXT
main.ts(2,13): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
main.ts(4,35): error TS2322: Type 'string' is not assignable to type 'number'.

TS2345 is the error for a bad function argument (here, the argument of push), and TS2322 is the general "this value doesn't fit that type" error. Change '100' to 100 and '3' to 3, and the program runs.

Reading elements: indexes and undefined

Here is a subtle point. When you read scores[5] from an array of three numbers, JavaScript gives you undefined, but by default TypeScript says the type is number. TypeScript doesn't track array lengths, so it trusts that the index exists.

TypeScript Indexing past the end

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is undefined, then 77.0, then no score above 100. Notice that at() and find() are honest: their return type includes undefined, so TypeScript makes you handle the missing case. Plain indexing is not.

The compiler option noUncheckedIndexedAccess fixes this by making scores[5] have the type number | undefined. It isn't part of --strict and our editor doesn't enable it, but many teams turn it on. You'll see it in The tsconfig.json File and again in Index Signatures and Record.

Multi-dimensional arrays

A grid, a board or a matrix is an array of arrays. Each extra dimension adds one more [] to the type: number[][] is a list of rows, and every row is a list of numbers. You read an element with one index per dimension.

TypeScript A two-dimensional array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is 6, then [ [ 10, 2, 3 ], [ 4, 5, 6 ] ], the flattened [ 10, 2, 3, 4, 5, 6 ], the transposed [ [ 10, 4 ], [ 2, 5 ], [ 3, 6 ] ], the three board lines with an X in the middle, and 6 for the cube. Two points to remember. First, rows may have different lengths (a "jagged" array), because TypeScript only tracks the element type, not the size; use a tuple such as [number, number, number][] if every row must have exactly three columns. Second, never build a grid with Array(3).fill([]): fill puts the same inner array in every slot, so pushing to one row changes all of them. Array.from({ length: 3 }, () => ...) creates a fresh row each time.

Readonly arrays

Many functions only read an array: they sum it, print it or search it. Mark the parameter readonly and TypeScript guarantees the function can't change the caller's data. You can write it two ways:

TypeScript
function average(values: readonly number[]): number { /* ... */ }
function average2(values: ReadonlyArray<number>): number { /* ... */ }

A readonly array has every non-mutating method (map, filter, slice, includes, ...) but no push, pop, sort, splice or index assignment.

TypeScript A function that promises not to modify

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This prints 20.5, then [ 18, 19, 21, 24 ], then the original [ 21, 19, 24, 18 ]. Passing the mutable temps to a readonly number[] parameter is fine: a mutable array can do everything a readonly one can. In sortedCopy, toSorted() would also work (it's an ES2023 method that returns a sorted copy), but the spread-then-sort version shows that copying turns a readonly array back into a normal one.

Now try to break the promise:

TypeScript Modifying a readonly array (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(2,10): error TS2540: Cannot assign to 'length' because it is a read-only property.
main.ts(3,3): error TS2542: Index signature in type 'readonly number[]' only permits reading.
main.ts(4,10): error TS2339: Property 'push' does not exist on type 'readonly number[]'.
main.ts(8,7): error TS4104: The type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type 'string[]'.

The last error is the important one: you can't "launder" a readonly array by assigning it to a mutable variable, because then someone could push through the second name.

readonly is a compile-time check only. The array is still a normal JavaScript array at runtime, and the type disappears when the code is compiled (see How TypeScript Works). If you need runtime protection, use Object.freeze(), which Readonly and Immutability compares in detail.

A good default: make array parameters readonly unless the function really needs to change them. It documents intent and catches accidental mutations, such as calling sort() (which sorts in place) on data you were handed.

Tuples: fixed length, typed positions

A tuple type lists the type at each position:

TypeScript
let entry: [string, number] = ['Ada', 36];

TypeScript now knows that entry[0] is a string, entry[1] is a number, and the length is exactly 2. Tuples shine when a function needs to return more than one value, and destructuring makes them pleasant to use (see destructuring in the JavaScript course):

TypeScript Returning a pair from a function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The program prints range: 2 to 9, then GRACE 86 false, then 3. Because each position has its own type, name.toUpperCase() and age + 1 both type-check without any checks.

Tuples aren't inferred automatically

An array literal is inferred as an array, not a tuple. ['Ada', 36] becomes (string | number)[], which loses the position information. To get a tuple you annotate it (as above), declare the function's return type, or use as const (covered in Literal Types and as const). The compiler also checks the length:

TypeScript Tuple mistakes (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(1,7): error TS2322: Type '[number, number, number]' is not assignable to type '[number, number]'.
  Source has 3 element(s) but target allows only 2.
main.ts(2,33): error TS2322: Type 'number' is not assignable to type 'string'.
main.ts(2,37): error TS2322: Type 'string' is not assignable to type 'number'.
main.ts(5,7): error TS2322: Type '(string | number)[]' is not assignable to type '[string, number]'.
  Target requires 2 element(s) but source may have fewer.
main.ts(7,19): error TS2493: Tuple type '[number, number]' of length '2' has no element at index '2'.

Indented lines are extra detail attached to the error above them. Line 5 shows the inference trap: loose is a plain array, so it can't be trusted to have exactly two elements in the right order.

Optional, rest and named elements

Real data isn't always a fixed pair. Tuple types have three extras.

Optional elements end with ? and must come after the required ones. The tuple's length becomes a union like 2 | 3.

Rest elements use ...T[] to say "then any number of these". A rest element can appear at the end, at the start or in the middle, but only once.

Named elements label each position. The labels don't change the type at all; they exist for readability and show up in editor tooltips, which is a real help with tuples like [number, number, number].

TypeScript Flexible tuple shapes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This prints 3 4, then ada: best 15 and linus: best none, then home/ada/notes 2048. Notice that rows is an array of tuples, ScoreRow[], a very common combination. The type keyword used here gives a name to a type so you can reuse it; Type Aliases explains it fully.

Tuple types with rest elements are also how TypeScript describes function parameter lists. When you later meet Parameters<typeof fn> in Built-in Utility Types, the result is a (named) tuple.

Readonly tuples

Tuples can be readonly too, and they often should be. A coordinate or an RGB value is a value, not a container you push into. Write readonly before the tuple type:

TypeScript
const origin: readonly [number, number] = [0, 0];
// origin[0] = 5;  // error TS2540: Cannot assign to '0' because it is a read-only property.

There's a surprising reason readonly tuples matter: a mutable tuple still has push. TypeScript allows pair.push(3) on a [number, number], because tuples are built on arrays, and the type quietly becomes wrong (it still claims a length of 2). A readonly tuple has no push at all.

TypeScript Readonly tuples and as const

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is [ 1, 2, 3 ] length type says 2, real length is 3, then 30, 200 and 12. The as const assertion tells TypeScript "treat this literal as exactly what it says": a readonly tuple whose elements are the literal types 10 and 20. A readonly tuple parameter accepts both as const tuples and fresh array literals like [3, 4], because TypeScript infers the literal as a tuple when the expected type is one (that's contextual typing, from Type Inference).

Arrays, tuples or objects?

A quick guide for choosing:

Use When Example
T[] / readonly T[] Any number of items of the same kind string[] of tags
Tuple A small, fixed group where position is obvious [min, max], [key, value]
Object type Several values where names matter { name: string; age: number }

Tuples are great for short-lived pairs, like a function returning two things or the [key, value] entries you get from Object.entries() and Map. Once there are three or more positions, or the data travels far through your code, an object with named properties is usually clearer: user.age explains itself, user[1] doesn't. Object types are the subject of the next lesson.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the inferred type of const values = [1, 'a', 2];?

    Array literals are inferred as arrays, not tuples. With mixed elements, the element type is the union string | number.
  2. 2. Does this compile? function f(xs: readonly number[]) { xs.sort(); }

    readonly number[] removes every mutating method, including sort. Copy first ([...xs].sort()) or use toSorted().
  3. 3. With default strict settings, what is the type of x in const xs: number[] = [1]; const x = xs[3];?

    Without noUncheckedIndexedAccess, indexing an array gives the element type even if the index is out of range. At runtime x is undefined.
  4. 4. Which value is NOT assignable to [string, ...number[]]?

    The first element must be a string and every later element a number. [1, 'a'] has them in the wrong order.
  5. 5. What is the type of const p = [3, 4] as const;?

    as const infers the narrowest type, a readonly tuple whose elements are the literal types 3 and 4.

Summary

  • T[] and Array<T> are the same type; TypeScript usually infers it. Mixed elements give an array of a union, like (string | number)[].
  • Annotate empty arrays you fill later: const errors: string[] = [];.
  • Plain indexing (xs[i]) is typed as the element type even past the end; at() and find() return T | undefined. noUncheckedIndexedAccess makes indexing honest too.
  • readonly T[] (or ReadonlyArray<T>) removes push, sort, index assignment and other mutations. Mutable arrays can be passed where readonly ones are expected, not the other way around. It's compile-time only.
  • A tuple like [string, number] has a fixed length and a type per position. Array literals aren't inferred as tuples unless the context asks for one or you use as const.
  • Tuples support optional (x?), rest (...T[]) and named (label: T) elements; prefer readonly tuples, because mutable tuples still allow push.
  • Use tuples for small fixed groups; switch to object types when names make the data clearer.

Next: Object Types