Understanding Tuple arrays in Typescript

In TypeScript, tuple arrays are a powerful feature that allows you to create fixed-length arrays with specific types for each element. These are useful when you want to define strict structures for your data.

Here’s an overview:

Defining a Tuple

A tuple is an array with a fixed number of elements, where each element has a specific type.

let tuple: [string, number];
tuple = ["hello", 42]; // Valid
// tuple = [42, "hello"]; // Error: Types don't match

Tuple Arrays

You can define an array of tuples by specifying the tuple type followed by [].

Example: Tuple Array

let tupleArray: [string, number][];

tupleArray = [
  ["apple", 10],
  ["banana", 20],
  ["cherry", 30],
];

Accessing Elements

TypeScript enforces the correct types for tuple elements:

const firstTuple = tupleArray[0];
console.log(firstTuple[0].toUpperCase()); // Access string element
console.log(firstTuple[1] + 5); // Access number element

Using with Functions

Tuple arrays work well with functions for passing structured data:

function processTuples(data: [string, number][]): void {
  data.forEach(([name, value]) => {
    console.log(`Name: ${name}, Value: ${value}`);
  });
}

processTuples(tupleArray);

Common Use Cases

  1. Coordinate Systems: let points: [number, number][] = [[0, 0], [1, 2], [3, 4]];
  2. Key-Value Pairs: let pairs: [string, number][] = [["one", 1], ["two", 2]];
  3. Tabular Data: Representing rows with structured fields.

Optional and Rest Elements

Tuples can have optional and rest elements for more flexibility:

Optional Elements

let optionalTuple: [string, number?];
optionalTuple = ["hello"];
optionalTuple = ["hello", 42];

Rest Elements

let restTuple: [string, ...number[]];
restTuple = ["hello", 1, 2, 3, 4];

Summary

Tuple arrays combine the benefits of tuples (strict typing) with arrays (dynamic sizing), making them highly versatile for structured data management in TypeScript. Use them when you want to enforce predictable structures in your code.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *