🌱BeginnerTypeScript Basics
Arrays and Tuples
Typed arrays (string[], Array<T>), readonly arrays, fixed-length tuples, and rest elements.
Overview
TypeScript extends JavaScript arrays with type safety. A `string[]` array will only ever hold strings TypeScript prevents you from accidentally pushing a number or accessing a property that strings don't have.
**Two equivalent syntaxes** for typed arrays: `Type[]` (shorthand) and `Array<Type>` (generic form). Both are the same; `Type[]` is more common for simple types, `Array<Type>` is clearer for complex types like `Array<string | null>`.
**Tuples** are fixed-length arrays where each position has a known type. `[string, number]` is a 2-element array where position 0 is a string and position 1 is a number. Tuples are useful for: function return values with mixed types, structured CSV-style data, and named tuples (TypeScript 4.0+).
**Readonly arrays** prevent mutation no `push`, `pop`, or index assignment. Use `readonly Type[]` or `ReadonlyArray<Type>` for data that should not change.
Key Points
- •`string[]` and `Array<string>` are identical prefer `string[]` for simple types
- •Array methods infer element types: `.map()`, `.filter()`, `.find()` all return typed results
- •Tuples: `[string, number]` fixed length, each position has its own type
- •Tuple labels (TS 4.0+): `[id: number, name: string]` same runtime, better IDE hints
- •`readonly string[]` / `ReadonlyArray<string>` no push, pop, or index writes
- •`as const` on an array literal makes it a readonly tuple of literal types
- •Rest elements in tuples: `[string, ...number[]]` one string then any number of numbers
Examples
Typed arrays
// Array type annotations
const names: string[] = ["Alice", "Bob", "Carol"];
const scores: number[] = [95, 87, 91];
const flags: boolean[] = [true, false, true];
// Generic syntax
const ids: Array<number> = [1, 2, 3];
const nullable: Array<string | null> = ["hello", null, "world"];
// Type-safe operations
names.push("Dave"); // ok
// names.push(42); // Error: Argument of type 'number' is not assignable
// TypeScript infers return types from array methods
const upper = names.map(n => n.toUpperCase()); // string[]
const high = scores.filter(s => s > 90); // number[]
const first = names.find(n => n.length > 3); // string | undefinedTuples fixed-length typed arrays
// Basic tuple
let point: [number, number] = [10, 20];
// point[0] is number, point[1] is number
// Mixed-type tuple
let userRow: [number, string, boolean] = [1, "Alice", true];
const [id, name, active] = userRow; // destructured with correct types
console.log(id, name, active);
// Labeled tuple (TypeScript 4.0+)
type Coordinate = [x: number, y: number, z?: number];
const origin: Coordinate = [0, 0];
const point3D: Coordinate = [1, 2, 3];
// Function returning a tuple
function minMax(arr: number[]): [number, number] {
return [Math.min(...arr), Math.max(...arr)];
}
const [min, max] = minMax([3, 1, 4, 1, 5, 9]);
console.log(min, max); // 1 9Readonly arrays immutable type-level protection
// readonly array prevents mutation
const CONFIG: readonly string[] = ["debug", "strict", "verbose"];
// CONFIG.push("fast"); // Error: Property 'push' does not exist on readonly
// CONFIG[0] = "quiet"; // Error: Index signature in type 'readonly string[]' only permits reading
// ReadonlyArray<T> is identical
const IDS: ReadonlyArray<number> = [1, 2, 3];
// as const infers a readonly tuple of literal types
const DIRECTIONS = ["north", "south", "east", "west"] as const;
// type: readonly ["north", "south", "east", "west"]
type Direction = typeof DIRECTIONS[number]; // "north" | "south" | "east" | "west"
// Functions can accept readonly arrays
function sum(nums: readonly number[]): number {
return nums.reduce((a, b) => a + b, 0);
}
console.log(sum([1, 2, 3])); // 6Common Mistakes
- Using `[]` to type an array `const arr: [] = []` is an empty tuple, not an array; use `string[]` or `Array<string>`
- Accessing tuple indices beyond their length TypeScript will error, but runtime will return undefined
- Passing a mutable array where a readonly is expected TypeScript allows this (readonly is a supertype), but not the reverse
Note
Prefer `readonly` for function parameters that shouldn't be mutated. This communicates intent and prevents bugs where a helper function accidentally modifies the caller's array.
Exercises
Write TypeScript code to solve each exercise. Click Run to compile and execute it right here, then mark as done.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4