arrays and tuples
Typed Arrays
In TypeScript, arrays are typed based on what kind of values they're allowed to hold. This prevents you from accidentally mixing incompatible values.
let scores: number[] = [85, 90, 78];
let names: string[] = ["Alice", "Bob"];
scores.push(100); // valid
scores.push("A+"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'Generic Array Syntax
Arrays can also be typed using the generic Array<T> form — functionally identical to T[].
let ids: Array = [1, 2, 3];
let labels: Array = ["a", "b", "c"]; Arrays of Objects
interface Product {
name: string;
price: number;
}
const products: Product[] = [
{ name: "Keyboard", price: 49.99 },
{ name: "Mouse", price: 19.99 }
];Union Type Arrays
An array can hold multiple allowed types using a union.
let mixed: (string | number)[] = ["a", 1, "b", 2];What is a Tuple?
A tuple is a special array with a fixed length and a known type for each position. This is different from a regular array, where every element must be the same type.
let user: [string, number];
user = ["Alice", 28]; // valid — string first, number second
user = [28, "Alice"]; // Error: wrong orderWhy Use Tuples?
Tuples are great for representing a fixed, meaningful combination of values — like coordinates, key-value pairs, or a name paired with an age.
let point: [number, number] = [10, 20];
function useCoordinates([x, y]: [number, number]): void {
console.log(`x: ${x}, y: ${y}`);
}
useCoordinates(point);Optional Tuple Elements
let entry: [string, number?];
entry = ["Alice"]; // valid, second element omitted
entry = ["Bob", 25]; // validNamed Tuple Members (Better Readability)
let range: [start: number, end: number];
range = [0, 100];Naming tuple members doesn't change how the tuple works, but makes the code far easier to read and understand at a glance.
Readonly Arrays and Tuples
Prevent accidental mutation by marking an array or tuple as readonly.
const roles: readonly string[] = ["admin", "editor", "viewer"];
roles.push("guest"); // Error: Property 'push' does not exist on type 'readonly string[]'
const point: readonly [number, number] = [5, 10];
point[0] = 99; // Error: Cannot assign to '0' because it is a read-only propertyArray vs Tuple — Quick Comparison
| Array | Tuple |
|---|---|
| Same type for every element | Each position can have its own specific type |
| Length can grow or shrink freely | Length is fixed by the type definition |
Example: number[] | Example: [string, number] |
Coming up next: Enums — how to define a named set of related constants.