🔷 TypeScript Q9 / 101

What is tuple type?

AI-Powered Answer ✓ Answered

A TypeScript tuple type is a special type of array that allows you to express an array with a fixed number of elements whose types are known, but don't have to be the same, at specific positions.

Understanding Tuples

Unlike regular arrays where all elements typically share the same type (or a union of types), a tuple precisely specifies the type of each element at each index. It's essentially an array with a predetermined structure and length.

Declaration Syntax

Tuples are declared by specifying a list of types within square brackets.

typescript
let person: [string, number, boolean];
person = ["Alice", 30, true]; // Valid
// person = [30, "Alice", true]; // Error: Type 'number' is not assignable to type 'string' at index 0.

Attempting to assign a value with an incorrect number of elements or incorrect types at specific positions will result in a compile-time error.

Accessing Elements and Destructuring

You can access elements of a tuple using their index, just like with arrays. Tuples also support array destructuring, which is a common pattern for extracting values.

typescript
let user: [string, number] = ["Bob", 42];

console.log(user[0]); // Output: Bob
console.log(user[1]); // Output: 42

let [name, age] = user;
console.log(name); // Output: Bob
console.log(age);  // Output: 42

Key Characteristics

  • Fixed Length: A tuple has a specific, fixed number of elements.
  • Ordered Types: The type of each element at each specific index is known and enforced.
  • Heterogeneous: Elements within a tuple can be of different types.

Use Cases

  • Returning Multiple Values: Functions that need to return several related but different types of values often use tuples.
  • Fixed-Structure Data: Representing data where the order and type of elements are crucial, such as [latitude, longitude], [r, g, b] color values, or [statusCode, errorMessage] for API responses.
  • Modeling Key-Value Pairs: When dealing with a fixed pair where the 'key' has a known type and the 'value' has another known type.
typescript
function fetchUser(): [number, string, boolean] {
  // Simulate fetching data
  return [101, "Jane Doe", true];
}

const [id, username, isActive] = fetchUser();
console.log(`User ID: ${id}, Username: ${username}, Active: ${isActive}`);

Read-Only Tuples

Like arrays, tuples can also be made readonly to prevent their elements from being modified after creation. This ensures immutability for the tuple's content.

typescript
let immutablePoint: readonly [number, number] = [10, 20];
// immutablePoint[0] = 5; // Error: Cannot assign to '0' because it is a read-only property.

Tuple vs. Array

FeatureTupleArray
LengthFixed and known at declarationVariable, can grow or shrink
Element TypesHeterogeneous (different types at different positions)Homogeneous (usually all same type, or union)
PurposeRepresents a structured record with ordered, typed fieldsRepresents a list of items of the same type
Usage Example`[string, number, boolean]``string[]` or `Array<number>`