Type System

TS Tuple Types

Using Tuple Types

TypeScript tuple types define fixed-length arrays with specific types.

What Are Tuple Types?

In TypeScript, tuple types allow you to express an array with a fixed number of elements whose types are known, but can be different. This is in contrast to normal arrays where each element shares the same type.

Tuples are useful when you want to represent a collection of values where the number and types of elements are known and need to be enforced.

Defining Tuple Types

To define a tuple type in TypeScript, you specify the types of elements within square brackets. Each type in the tuple can be different, and the order matters.

Here is a simple example of a tuple type:

In this example, person is defined as a tuple type that expects the first element to be a string and the second element to be a number.

Working with Tuple Types

Once a tuple type is defined, you can assign values to it that match the specified types and order. Let's see how you can work with tuples:

The tuple person is correctly assigned with a string as the first element and a number as the second. TypeScript will enforce the order and types of elements, helping you catch errors at compile time.

Accessing and Modifying Tuple Elements

You can access and modify elements in a tuple using index notation, similar to arrays. Here's an example:

This code demonstrates how to access the elements of a tuple using their index, and how to modify the elements while maintaining the correct type.

Using Tuples with Functions

Tuples can be used in functions, either as parameters or return types. This can be useful when you want a function to return multiple values of different types.

In this example, the function getPerson returns a tuple, and we use destructuring to assign the returned values to variables.

Conclusion

TypeScript's tuple types are a powerful feature for defining arrays with a fixed length and specific types. By enforcing the types and order of elements, tuples help improve the type safety of your code, making it easier to catch errors early in the development process.