TypeScript FoundationsLesson 1.4
TypeScript arrays and tuples explained with examples
array type syntax, generic array syntax, readonly arrays, tuple definition, tuple use cases, tuple vs array
Arrays in TypeScript
Two equivalent ways to type an array:
// Both mean the same thing
const names: string[] = ["alice", "bob"];
const scores: Array = [98, 85, 91];
// Mixed types require a union
const mixed: (string | number)[] = ["a", 1, "b", 2];TypeScript enforces the element type. Pushing the wrong type throws an error:
names.push(42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'Readonly arrays
const ids: readonly number[] = [1, 2, 3];
ids.push(4); // Error: Property 'push' does not exist on type 'readonly number[]'Tuples
A tuple is a fixed-length array where each position has a specific type:
// [name, age, isAdmin]
const user: [string, number, boolean] = ["alice", 30, true];
const name = user[0]; // string
const age = user[1]; // numberTuples are useful for functions that return multiple values of different types:
function getCoords(): [number, number] {
return [40.71, -74.00];
}
const [lat, lng] = getCoords();