Tuple Type in TypeScript

  • In TypeScript, a tuple type represents an array with a fixed number of elements, where each element can have its own specific type. The order of the elements is significant, and the types of the elements are known at compile-time.
  • To declare a tuple type, you use square brackets `[]` and specify the types of the elements in order, separated by commas. Here's an example:


    let tuple: [string, number, boolean] = ["hello", 42, true];

  • In the example above, `tuple` is declared as a tuple with three elements. The first element is a string, the second element is a number, and the third element is a boolean.
  • You can access individual elements of a tuple using zero-based indexing:


    console.log(tuple[0]); // Output: "hello"
    console.log(tuple[1]); // Output: 42
    console.log(tuple[2]); // Output: true

  • Tuple types can be useful when you want to represent a collection of values with different types, but the number of elements and their types are fixed and known.


    let tuple: [string, number, boolean, number?] = ["hello", 42, true];
    tuple.push(78)
    console.log(tuple[0]); // Output: "hello"
    console.log(tuple[1]); // Output: 42
    console.log(tuple[2]); // Output: true
    console.log(tuple[3]); // Output: 78

  • It's worth noting that TypeScript also provides additional utility types for working with tuples, such as `readonly`, `Partial`, and `Pick`. These utility types can help you define more specific constraints and transformations on tuples.

No comments:

Post a Comment