Working with arrays and tuples in TypeScript.
Arrays
Array Type Syntax
// Method 1: Type[]
let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ["Alice", "Bob", "Charlie"];
// Method 2: Array<Type>
let numbers2: Array<number> = [1, 2, 3, 4, 5];
let names2: Array<string> = ["Alice", "Bob", "Charlie"];
Array Operations
let numbers: number[] = [1, 2, 3];
// Adding elements
numbers.push(4);
numbers.unshift(0);
// Removing elements
numbers.pop();
numbers.shift();
// Accessing elements
let first = numbers[0];
let last = numbers[numbers.length - 1];
// Iterating
for (let num of numbers) {
console.log(num);
}
numbers.forEach(num => console.log(num));
Readonly Arrays
let readonlyNumbers: readonly number[] = [1, 2, 3];
// readonlyNumbers.push(4); // ❌ Error: Property 'push' does not exist
// Or use ReadonlyArray<T>
let readonlyNumbers2: ReadonlyArray<number> = [1, 2, 3];
Array Methods with Types
let numbers: number[] = [1, 2, 3, 4, 5];
// map
let doubled: number[] = numbers.map(n => n * 2);
// filter
let evens: number[] = numbers.filter(n => n % 2 === 0);
// reduce
let sum: number = numbers.reduce((acc, n) => acc + n, 0);
// find
let found: number | undefined = numbers.find(n => n > 3);
// some
let hasEven: boolean = numbers.some(n => n % 2 === 0);
Tuples
Tuples are arrays with a fixed number of elements and specific types.
Basic Tuple
let person: [string, number] = ["Alice", 25];
// person = [25, "Alice"]; // ❌ Error: Type 'number' is not assignable to type 'string'
let first: string = person[0]; // "Alice"
let second: number = person[1]; // 25
Named Tuples (TypeScript 4.0+)
let person: [name: string, age: number] = ["Alice", 25];
// More readable and self-documenting
Optional Tuple Elements
let optionalTuple: [string, number?] = ["Alice"];
// Second element is optional
Rest Elements in Tuples
let tuple: [string, ...number[]] = ["Alice", 1, 2, 3, 4];
// First element is string, rest are numbers
Readonly Tuples
let readonlyTuple: readonly [string, number] = ["Alice", 25];
// readonlyTuple[0] = "Bob"; // ❌ Error: Cannot assign to '0' because it is a read-only property
Common Use Cases
Coordinates
type Point = [number, number];
let point: Point = [10, 20];
Key-Value Pairs
type KeyValue = [string, any];
let entry: KeyValue = ["name", "Alice"];
Function Returns
function getStatus(): [boolean, string] {
const success = true;
const message = "Operation completed";
return [success, message];
}
const [success, message] = getStatus();
React useState Hook
// useState returns a tuple
const [count, setCount] = useState<number>(0);
// count: number
// setCount: (value: number) => void
Array Type Inference
// TypeScript infers: number[]
let numbers = [1, 2, 3];
// TypeScript infers: (string | number)[]
let mixed = ["hello", 42, "world"];
// TypeScript infers: [string, number]
let tuple = ["Alice", 25] as const;
Exercises
Exercise 1: Arrays
// Create an array of numbers and:
// - Find the sum of all numbers
// - Find the maximum number
// - Create a new array with each number doubled
Exercise 2: Array Types
// Create a function that:
// - Takes an array of strings
// - Returns an array of strings in uppercase
// - Has proper type annotations
Exercise 3: Tuples
// Create a tuple type for RGB color:
// - [number, number, number] representing red, green, blue values (0-255)
// - Create a function that takes RGB and returns a hex color string
Exercise 4: Tuple Returns
// Create a function 'divide' that:
// - Takes two numbers
// - Returns a tuple [result: number, remainder: number]
Exercise 5: Readonly Arrays
// Create a readonly array of configuration values
// Try to modify it and see the error
Best Practices
- Use arrays for variable-length collections - When size is unknown
- Use tuples for fixed-length collections - When structure is known
- Prefer readonly when appropriate - For immutable data
- Use type aliases for complex types - Makes code more readable
- Leverage array methods - map, filter, reduce are type-safe
Common Mistakes
- Confusing arrays and tuples
// ❌ Bad - treating tuple as array
let point: [number, number] = [10, 20];
point.push(30); // Runtime works, but breaks tuple contract
// ✅ Good - use array if length varies
let coordinates: number[] = [10, 20];
coordinates.push(30);
- Not using readonly for immutable arrays
// ❌ Bad
const config: string[] = ["api", "db", "cache"];
// ✅ Good
const config: readonly string[] = ["api", "db", "cache"];
- Forgetting tuple element types
// ❌ Bad - loses type safety
let person: any[] = ["Alice", 25];
// ✅ Good
let person: [string, number] = ["Alice", 25];
Next Steps
Learn about Enums.