Arrays and Tuples in TypeScript
Arrays and Tuples in TypeScript
Section titled “Arrays and Tuples in TypeScript”Array Syntax
Section titled “Array Syntax”// Two equivalent syntaxeslet numbers: number[] = [1, 2, 3];let names: Array<string> = ["Alice", "Bob"];
// Multi-dimensionallet matrix: number[][] = [[1, 2], [3, 4]];let cube: number[][][] = [[[1]]];
// Union arrayslet mixed: (string | number)[] = ["hello", 42];Readonly Arrays
Section titled “Readonly Arrays”let readOnly: readonly number[] = [1, 2, 3];let readOnly2: ReadonlyArray<string> = ["a", "b"];
// readOnly.push(4); // ❌ Error// readOnly[0] = 10; // ❌ Error
// Readonly prevents mutation methodsTuple Types
Section titled “Tuple Types”// Fixed-length array with specific typeslet person: [string, number] = ["Alice", 30];
// Access preserves typesperson[0].toUpperCase(); // string method — OKperson[1].toFixed(2); // number method — OK
// Optional tuple elementslet tuple: [string, number?] = ["hello"];tuple = ["hello", 42]; // Also OK
// Labeled tuples (TS 4.0+)type Range = [start: number, end: number];type Name = [firstName: string, lastName: string];Rest Elements in Tuples
Section titled “Rest Elements in Tuples”// Variable length with fixed prefixtype StringsWithNumbers = [string, ...number[]];let a: StringsWithNumbers = ["hello", 1, 2, 3];
// Rest at starttype LeadingRest = [...number[], string];let b: LeadingRest = [1, 2, 3, "end"];
// Multiple rests (TS 4.2+)type Mixed = [string, ...number[], boolean];Real-World Tuple Patterns
Section titled “Real-World Tuple Patterns”// React useState returntype UseStateResult<T> = [T, (value: T) => void];
// API response pairtype ApiResult<T> = [T | null, Error | null];
// CSV rowtype CsvRow = [name: string, age: number, email: string];Interview Questions
Section titled “Interview Questions”Easy: How do you declare an array of numbers in TypeScript?
Medium: What is the difference between type[] and [type, type]?
Hard: How would you type a function that returns a tuple with labeled elements?