Tuple Types
Tuple Types
Section titled “Tuple Types”What it is
Section titled “What it is”Tuple types are arrays with fixed length where each element can have a specific type. They provide type safety for fixed-length arrays.
Before this feature
Section titled “Before this feature”Arrays couldn’t enforce length or per-element types:
// Regular array - any length, same typeconst coords: number[] = [10, 20, 30]; // OK but not ideal for x,yAfter this feature
Section titled “After this feature”Tuples provide precise type definitions:
// Basic tuplelet point: [number, number] = [10, 20];// point[0] is number// point[1] is number// point[2] = 30; // Error - length is 2
// Mixed typeslet user: [string, number, boolean];user = ["Alice", 25, true]; // OKuser = [25, "Alice", true]; // Error - wrong types
// Tuple as function returnfunction getUser(): [string, number] { return ["Alice", 25];}
const [name, age] = getUser();// name is string, age is number
// Optional elementstype Point3D = [number, number, number?];const p1: Point3D = [10, 20]; // OKconst p2: Point3D = [10, 20, 30]; // OK
// Rest elementstype StringNumberBooleans = [string, number, ...boolean[]];const arr1: StringNumberBooleans = ["hello", 42];const arr2: StringNumberBooleans = ["hello", 42, true, false];
// Named tuple elements (TS 4.0+)type Range = [start: number, end: number];type User = [name: string, age: number];
// Readonly tuplesconst config: readonly [string, number] = ["version", 1];// config[0] = "v2"; // Error
// Tuple types in destructuringfunction swap<T, U>(tuple: [T, U]): [U, T] { return [tuple[1], tuple[0]];}
const result = swap([1, "a"]); // [string, number]Why this is better
Section titled “Why this is better”- Type safety: Each element has specific type
- Fixed length: Enforces array size
- Destructuring: Works great with destructuring
- Function returns: Multiple typed return values
- Documentation: Types serve as documentation
Key notes / edge cases
Section titled “Key notes / edge cases”- Length is part of the type
- Can have optional elements at end
- Rest elements for variable length
- Named elements improve readability
- Readonly tuples prevent mutation
// Array methods work but may break typeconst tuple: [number, string] = [1, "a"];tuple.push("b"); // Allowed but breaks tuple typeconsole.log(tuple); // [1, "a", "b"]
// Use readonly to preventconst safe: readonly [number, string] = [1, "a"];// safe.push("b"); // Error
// Tuple with labels (better docs)type HTTP = [ url: string, method: "GET" | "POST", status: number];
// Variadic tuples (TS 4.0+)type Concat<T extends unknown[], U extends unknown[]> = [...T, ...U];type Result = Concat<[1, 2], [3, 4]>; // [1, 2, 3, 4]Quick practice
Section titled “Quick practice”-
Define a tuple for [id: number, name: string, active: boolean]
Answer
type User = [number, string, boolean];// or with labelstype User = [id: number, name: string, active: boolean]; -
Create a function returning a tuple of [success: boolean, message: string]
Answer
function validate(input: string): [boolean, string] {if (input.length > 0) {return [true, "Valid"];}return [false, "Invalid"];} -
What’s the difference between
[number, string]and(number | string)[]?Answer
`[number, string]` is a tuple: exactly 2 elements, first is number, second is string. `(number | string)[]` is an array: any length, each element can be number OR string.