Arrays and Tuples in TypeScript
Understand how to work with arrays and tuples in TypeScript. We'll cover declaring, initializing, and manipulating these data structures.
Introduction to Arrays and Tuples in TypeScript
Welcome to the world of data structures in TypeScript! This tutorial will guide you through the fundamentals of two essential structures: Arrays and Tuples. We'll explain what they are, how they work, and when you might use them. Don't worry if you're completely new to TypeScript - we'll keep it simple!
Arrays in TypeScript
An array is a collection of items, all of the same type (though in TypeScript, you *can* create arrays with mixed types if you really need to, but it's generally discouraged). Think of it like a list where you store multiple values under a single variable name.
Declaring Arrays
There are two common ways to declare an array in TypeScript:
- Using the Type followed by Square Brackets
[]
: This is the most common and readable approach. - Using the
Array<Type>
generic type: This is functionally equivalent but less frequently used for simple cases.
// Method 1: Type followed by []
let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ["Alice", "Bob", "Charlie"];
let booleans: boolean[] = [true, false, true];
// Method 2: Array<Type> (Generic Type)
let numbers2: Array<number> = [1, 2, 3, 4, 5]; // Same as number[]
let names2: Array<string> = ["Alice", "Bob", "Charlie"]; // Same as string[]
In the examples above:
number[]
indicates an array that can only hold numbers.string[]
indicates an array that can only hold strings.boolean[]
indicates an array that can only hold boolean values.
Accessing Array Elements
You can access elements within an array using their index. Remember that array indices start at 0 (not 1)!
let fruits: string[] = ["apple", "banana", "orange"];
console.log(fruits[0]); // Output: apple
console.log(fruits[1]); // Output: banana
console.log(fruits[2]); // Output: orange
// Trying to access an index that doesn't exist will result in `undefined`.
console.log(fruits[3]); // Output: undefined
Array Methods
TypeScript (and JavaScript) provides many built-in methods for working with arrays. Here are a few common ones:
push(element)
: Adds an element to the end of the array.pop()
: Removes the last element from the array and returns it.shift()
: Removes the first element from the array and returns it.unshift(element)
: Adds an element to the beginning of the array.length
: A property that returns the number of elements in the array.map(callback)
: Creates a new array with the results of calling a provided function on every element in the calling array.filter(callback)
: Creates a new array with all elements that pass the test implemented by the provided function.
let colors: string[] = ["red", "green", "blue"];
colors.push("yellow"); // Adds "yellow" to the end
console.log(colors); // Output: ["red", "green", "blue", "yellow"]
let lastColor = colors.pop(); // Removes "yellow"
console.log(lastColor); // Output: yellow
console.log(colors); // Output: ["red", "green", "blue"]
console.log(colors.length); // Output: 3
let doubledNumbers: number[] = [1, 2, 3].map(num => num * 2);
console.log(doubledNumbers); // Output: [2, 4, 6]
let evenNumbers: number[] = [1, 2, 3, 4, 5, 6].filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6]
Tuples in TypeScript
A tuple is another type of data structure, similar to an array, but with a fixed number of elements and each element can have a different type. Tuples are useful when you know the exact structure and types of the data you're working with.
Declaring Tuples
You declare a tuple by specifying the type of each element within square brackets:
let person: [string, number, boolean] = ["John Doe", 30, true];
// person[0] is a string (the name)
// person[1] is a number (the age)
// person[2] is a boolean (whether they are active)
Accessing Tuple Elements
You access tuple elements using their index, just like with arrays:
let product: [string, number] = ["Laptop", 1200];
console.log("Product Name:", product[0]); // Output: Product Name: Laptop
console.log("Product Price:", product[1]); // Output: Product Price: 1200
Why Use Tuples?
Tuples provide better type safety than arrays when you need to represent a fixed collection of values with known types. TypeScript will enforce that the elements in the tuple match the defined types, helping you catch errors early in development.
// Example of a potential error:
let point: [number, number] = [10, 20];
// This will cause a TypeScript error because we are assigning a string to the second element which is a number.
// point[1] = "Hello"; // ERROR: Type 'string' is not assignable to type 'number'.
Tuple Use Cases
- Representing coordinates (e.g.,
[x, y]
). - Representing a record with a specific structure (e.g.,
[name, age, city]
). - Returning multiple values from a function where each value has a distinct type.
Readonly Tuples
You can make tuples readonly so that their elements cannot be modified after initialization. This is useful for preventing accidental mutations.
let readonlyPoint: readonly [number, number] = [5, 10];
// readonlyPoint[0] = 20; // ERROR: Cannot assign to '0' because it is a read-only property.
//Alternative way to define readonly tuple
let readonlyPoint2: ReadonlyArray = [5, 10];
// readonlyPoint2[0] = 20; // ERROR: Index signature in type 'readonly number[]' only permits reading.
Arrays vs. Tuples: Key Differences
Feature | Array | Tuple |
---|---|---|
Fixed Size? | No (can grow or shrink) | Yes (fixed number of elements) |
Element Types | Generally, all elements should be of the same type (though any[] is possible) | Elements can be of different types |
Type Safety | Less strict; can be more prone to runtime errors if not carefully managed | More strict; TypeScript enforces type constraints at compile time |
Use Cases | Storing collections of similar items (e.g., list of users, list of products) | Representing structured data with a fixed format (e.g., coordinates, database records) |
In summary, choose arrays when you need a flexible collection of items, and choose tuples when you need a fixed-size structure with specific types for each element.