TypeScriptBasic types

Arrays: number[] and Array<T>

Array types, where every element has the same type.

On this page

Example

#
TypeScript
const scores: number[] = [72, 95, 88]
const names: Array<string> = ['Emma', 'Jack']

scores.push(64)
const best = Math.max(...scores)
console.log(best, names.length)
Result
95 2

Definition and usage

#

You describe an array by adding square brackets to the element type: number[] is an array of numbers, string[] an array of strings. An equivalent notation is the generic type Array<number>.

That way the compiler knows the type of every element and suggests the right methods. After names.map(...), it knows the callback receives a string, and trying to add a number to an array of strings fails.

You write a read-only array as readonly string[] or ReadonlyArray<string>. The compiler then blocks methods that mutate the array, like push().

Syntax

#
Syntax
let numbers: number[] = [1, 2, 3]
let strings: Array<string> = ["a", "b"]

More examples

#
A read-only array
TypeScript
const levels: readonly string[] = ['easy', 'medium', 'hard']
levels.push('expert')
// Error: Property 'push' does not exist on type 'readonly string[]'.
An array of objects
TypeScript
const lessons: { title: string; minutes: number }[] = [
  { title: 'Tags', minutes: 12 },
  { title: 'Attributes', minutes: 9 }
]

const total = lessons.reduce((sum, lesson) => sum + lesson.minutes, 0)
console.log(total)
Result
21

Good practices

#
  • Pick one notation (T[] or Array<T>) and stick with it across the project. You’ll see T[] more often.
  • For a fixed-length array with a different type at each position, use a tuple.

Related entries

#

Spotted a mistake or missing an example? Write to us.