Arrays

Arrays store ordered collections of values. In TypeScript, arrays are typed—you specify what kind of elements they can contain.
const numbers: number[] = [1, 2, 3, 4, 5]
const names: 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> vs readonly 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: Two Approaches

You can add elements to arrays in two ways:
// Mutation (modifies the original array)
const numbers: Array<number> = [1, 2, 3]
numbers.push(4)

// Immutable (creates a new array)
const numbers: Array<number> = [1, 2, 3]
const moreNumbers = [...numbers, 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.
When is mutation okay? If you're building an array locally inside a function and not sharing the reference, push() is perfectly fine. The immutable pattern matters most when data is shared or returned. Pragmatism over purity—choose the approach that's clearest for your situation.

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.