Arrays and Tuples
Collections of data are fundamental to any application. TypeScript enhances JavaScript arrays and introduces a fixed-length collection type known as a Tuple.
1. Array Types
In TypeScript, you can define array types in two ways. Both methods work exactly the same way under the hood.
Syntax Options
// Option A: Using square brackets
const scores: number[] = [85, 92, 78];
// Option B: Using generic Array type
const names: Array<string> = ["Alice", "Bob", "Charlie"];If you try to push a value of a different type into these arrays, the compiler will raise an error:
// Error: Argument of type 'boolean' is not assignable to parameter of type 'number'.
scores.push(true); 2. Read-Only Arrays
If you want to prevent an array from being modified after creation, use the ReadonlyArray type or the readonly modifier.
const constants: readonly number[] = [3.14, 2.71];
// This will fail compiler checks:
// constants.push(1.41);
// constants[0] = 9.9;This is useful for protecting configuration values or maintaining data immutability.
3. Tuples: Fixed-Length Arrays
A Tuple is an array type where you specify the exact number of elements and the exact type of each element at specific index positions.
Basic Tuple Example
let responseStatus: [number, string];
responseStatus = [200, "OK"]; // Correct
// responseStatus = ["OK", 200]; // Error: Type 'string' is not assignable to type 'number'.Deconstructing Tuples
You can deconstruct tuples into individual variables just like JavaScript arrays:
const [statusCode, statusMessage] = responseStatus;
console.log(statusCode); // 2004. Advanced Tuple Patterns
Tuples can contain optional elements or rest parameters, enabling complex configurations.
Optional Tuple Elements
You can use a question mark to specify that certain trailing elements are optional:
let point3D: [number, number, number?];
point3D = [10, 20]; // Valid
point3D = [10, 20, 30]; // ValidNamed Tuple Elements
TypeScript supports named tuple elements. These do not affect how the code compiles, but they improve editor autocompletion and code readability:
type Position = [x: number, y: number, z?: number];
const myPosition: Position = [50, 100];5. Summary
- Define array types using
type[]orArray<type>. - Use
readonlyarrays to prevent modifications. - Tuples define arrays with fixed lengths and specific types per position.
- Named elements in tuples provide better context in your editor.