Working with TypeScript Arrays and Tuples

TypeScript extends JavaScript with additional type features, making it easier to work with complex data structures like arrays and tuples. This guide will introduce you to arrays and tuples in TypeScript, including how to define, manipulate, and use them effectively.

TypeScript Arrays

Arrays in TypeScript are similar to arrays in JavaScript but come with the added benefit of type annotations. This ensures that all elements in the array conform to a specific type.

Defining Arrays

To define an array in TypeScript, you specify the type of its elements followed by []:

let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ["Alice", "Bob", "Charlie"];

In this example, numbers is an array of number and names is an array of string.

Array Methods

TypeScript arrays support various methods similar to JavaScript arrays. Here are some common methods:

  • push(): Adds an element to the end of the array.
  • pop(): Removes the last element of the array.
  • shift(): Removes the first element of the array.
  • unshift(): Adds an element to the beginning of the array.
  • map(): Creates a new array by applying a function to each element.

Array Example

let numbers: number[] = [1, 2, 3, 4, 5];
numbers.push(6); // [1, 2, 3, 4, 5, 6]
let doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10, 12]

TypeScript Tuples

Tuples are a special type of array in TypeScript where each element can have a different type. Tuples are useful when you need to work with a fixed number of elements of varying types.

Defining Tuples

To define a tuple, use square brackets [] with specified types for each element:

let person: [string, number] = ["Alice", 30];

In this example, person is a tuple where the first element is a string and the second element is a number.

Accessing Tuple Elements

Access tuple elements using their index, similar to arrays:

let person: [string, number] = ["Alice", 30];
let name = person[0]; // "Alice"
let age = person[1]; // 30

Tuple with Optional Elements

Tuples can also include optional elements:

let person: [string, number?] = ["Alice"];
let personWithAge: [string, number?] = ["Bob", 30];

In this example, the second element in the tuple is optional.

Conclusion

TypeScript arrays and tuples offer powerful ways to handle collections of data with strong type safety. By understanding how to define, manipulate, and use arrays and tuples, you can write more robust and maintainable code. Use arrays for lists of homogeneous data and tuples for fixed-size collections with heterogeneous data.