Arrays
Intro to Arrays
Arrays store ordered collections of values. In TypeScript, arrays are typedβyou
specify what kind of elements they can contain.
const numbers: Array<number> = [1, 2, 3, 4, 5]
const names: Array<string> = ['Alice', 'Bob', 'Charlie']
Two Syntax Options
TypeScript offers two ways to write array types:
// Square bracket syntax (shorter)
const numbers: number[] = [1, 2, 3]
// Generic syntax (preferred)
const numbers: Array<number> = [1, 2, 3]
Both are functionally identical. The square bracket syntax is shorter and you'll
see it frequently in codebases. However, the generic syntax (
Array<Type>) is
preferred for several reasons:- Readability: We read left-to-right, so "Array of numbers" reads more naturally than "numbers... array"
- Consistency with readonly:
ReadonlyArray<string>vsreadonly string[] - Union types:
Array<string | number>vs(string | number)[](no parentheses needed) - Works better with
keyof: Avoids confusing operator precedence issues
For a deeper dive into why generic notation is better, check out
Array Types in TypeScript
by TkDodo.
We'll use the generic syntax going forward in this workshop.
Type Safety with Arrays
TypeScript ensures you only put the right types in arrays:
const numbers: Array<number> = [1, 2, 3]
numbers.push(4) // β
OK
numbers.push('five') // β Error: 'string' not assignable to 'number'
Adding to Arrays
You can add elements to arrays in two ways:
const numbers: Array<number> = [1, 2, 3]
numbers.push(4)
The immutable approach using spread (
...) is often preferred in modern
JavaScript because it's easier to reason aboutβthe original array stays
unchanged. This is especially important when working with shared data or React
state. We'll talk about this in more detail in the next exercise.Mixed Arrays
Need different types? Use union types:
const mixed: Array<string | number> = [1, 'two', 3, 'four']
In this exercise, you'll create and work with typed arrays.