TypeScript Tuples: Structured Data with Ordered Types

Explore TypeScript tuples, a versatile data structure for storing elements of different types in a specific order. Learn how to create, access, and manipulate tuples to effectively represent and manage structured data.



TypeScript Tuples

Meta Description: Learn about TypeScript tuples, a data structure for storing elements of different types in a specific order. Discover how to create, access, and manipulate tuples effectively.

Understanding Tuples

A TypeScript tuple is a special array-like structure that allows you to store elements of different data types in a specific order. Unlike arrays, which can hold elements of the same type, tuples enforce type safety and provide a way to represent structured data.

Syntax:

Syntax

let tupleName: [type1, type2, ...] = [value1, value2, ...];

Creating and Accessing Tuples

Syntax

let employee: [number, string] = [1, "John Doe"];

console.log(employee[0]); // Output: 1
console.log(employee[1]); // Output: "John Doe"
Output

1
"John Doe"

Tuple Length and Type Safety

TypeScript ensures that the number of elements in a tuple matches the declared types. Trying to access an index beyond the defined length will result in a compile-time error.

Syntax

let point: [number, number] = [10, 20];
// point[2] = 30; // Error: Index out of bounds

Modifying Tuple Elements

While tuples are generally immutable, you can modify existing elements as long as the assigned value matches the declared type:

Syntax

let employee: [number, string] = [1, "John Doe"];
employee[1] = "Jane Smith"; // Valid
// employee[0] = "New ID"; // Error: Type 'string' is not assignable to type 'number'

Tuple Arrays

You can create arrays of tuples:

Syntax

let employees: [number, string][] = [
  [1, "Alice"],
  [2, "Bob"],
  [3, "Charlie"]
];

Key Points

  • Tuples provide a way to represent structured data with different types.
  • Tuple elements are accessed by index, similar to arrays.
  • TypeScript enforces type safety for tuple elements.
  • Tuples can be used to represent records, function return values, and more.

Use Cases

  • Function return values with multiple values of different types.
  • Representing data structures with known elements and types.
  • Creating immutable data structures.

By understanding tuples, you can write more expressive and type-safe TypeScript code.