TypeScript Reference ยท Primitive and Special Types
TypeScript Array<T> and T[] types
Reference for TypeScript array types: T[] and Array<T>, inference, empty arrays, typed methods like map and filter, index access and noUncheckedIndexedAccess.
An array type describes a list whose elements all share one type. TypeScript gives you two spellings that mean exactly the same thing: T[] and Array<T>. The first is shorter and more common; the second is the generic form and is handy when the element type is long or itself an array type.
Array methods are generic, so their results are typed from the element type: map returns a new array of whatever your callback returns, filter keeps the element type, and find returns T | undefined.
const scores: number[] = [90, 72]; const names: Array<string> = ["Ada", "Grace"];
Try it
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.
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.
Syntax
let a: T[]; let b: Array<T>; let c: (A | B)[]; // parentheses needed for unions let d: readonly T[]; let e: T[][]; // array of arrays
| Part | Description |
|---|---|
T[] |
Array whose elements are T. |
Array<T> |
Same type, generic spelling. |
(A | B)[] |
Array of a union. Without parentheses `A |
readonly T[] |
Array you cannot mutate through this reference. |
Edge cases:
- Indexing
a[i]givesT, even when the index is out of range, unlessnoUncheckedIndexedAccessis on (then it isT | undefined). const xs = []starts as an evolving array type: its element type grows from what you push, and reading it before anything is assigned can give an implicit-anyerror undernoImplicitAny.- Array literals of mixed values are inferred as a union array, for example
(string | number)[], not as a tuple.
Usage notes
- Pick one style. Many teams write
T[]for simple types andArray<...>for complex ones; linters can enforce it. - Methods are generic.
map<U>,reduce<U>,flatMap<U>and others inferUfrom your callback. filterwith a type guard narrows:xs.filter((x): x is string => typeof x === "string")returnsstring[].- Arrays are covariant in TypeScript.
string[]is assignable to(string | number)[], which means writing through the wider reference can break the original's promise. Usereadonlyarrays when you only read. - Use tuples for fixed shapes. If position matters, see Tuples.
- Holes and sparse arrays are not tracked by the type system.
- Newer methods such as
toSorted,toReversed,with(ES2023) andfindLastneed a suitablelib/target; ES2024 includes them.