TypeScript Tuple Types: The What, Why, and How

Discover TypeScript tuple types with examples.

TypeScript Tuple Types: The What, Why, and How

TypeScript is a tool that helps JavaScript developers write better code by allowing them to define rules for the types of data they want to use. By doing this, TypeScript makes it easier to ensure that the code works correctly and reduces the risk of errors.

In this article, we're going to explore the concept of tuple types in TypeScript, which is just one of the many data types that TypeScript supports. We'll cover what tuple types are, why they're useful, and provide some examples to help you understand how to use them.

What are tuple types? πŸ€”

In TypeScript, a tuple is a finite ordered list of elements that can have different data types. Tuples are similar to arrays in that they can store multiple values, but unlike arrays, tuples have a fixed length and their elements can have different data types.

To demonstrate a tuple type in TypeScript, let's consider a simple example of an Open Source user data that includes their name and total commits.

const user: [string, number] = ['Sachin Chaurasiya',3099]

Another great example of tuple types in action is in ReactJS hooks, where they're used as a return type to represent structured data.

// Example from react types
function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];

In this case, the tuple type [S, Dispatch<SetStateAction<S>>] contains two elements: the first element is of type S and represents the data being stored, while the second element is a dispatch function with the same type as the first element, which is used to update the stored data.

Why tuple types are useful? πŸ€”

Tuple types can be useful for a few reasons,

  • Tuple types allow you to represent a collection of values that have a specific order and data type.

  • Tuple types can be used to return multiple values from a function without having to create a custom object or array.

  • Tuple types make it easier to ensure that the data you're working with is structured correctly.

Now that we've covered what tuple types are and why they're beneficial, let's dive into some examples to understand their usage better.

Usage ✨

Suppose we want to store a user's Open Source contributions data, including their name and the number of commits they've made. In this scenario, using tuple types would be an appropriate solution.

type UserContribution = [string, number];

const getUserContribution = (user: User): UserContribution => {
  const name = `${user.firstName} ${user.lastName}`;
  const totalCommits = fetchCommits(user.userName);

  return [name, totalCommits];
};

In this scenario, we are using the UserContribution tuple type as the return type of the getUserContribution function to ensure that we receive structured data.

Accessing the tuple-type data

Accessing data in a tuple type is similar to accessing elements in an array, using indexes. However, with tuples, we have a fixed length and know exactly what type of data is stored at each index.

const userData: User = {
  firstName: "Sachin",
  lastName: "Chaurasiya",
  userName: "Sachin-chaurasiya",
};

const userContribution = getUserContribution(userData);

console.log(userContribution[0]); // Sachin Chaurasiya
console.log(userContribution[1]); // 3099

What happens if we try to access an index that is outside the bounds of the tuple?

if we try to access an index that is outside the bounds of the tuple then TypeScript will throw an error.

console.log(userContribution[2]) 

// Tuple type 'UserContribution' of length '2' has no element at index '2'.

Destructuring the tuple-type data

To avoid issues with out-of-bounds indexes, we can use JavaScript destructuring like the following.

const [user, totalCommits] = getUserContribution(userData);

Readonly tuple types

In certain scenarios, we may not want certain pieces of data to be modified. In these cases, we can use readonly tuple types.

In our scenario, we don't want anyone to modify the userContribution data after it has been defined, so we can modify the UserContribution tuple type to be readonly.

type UserContribution = readonly [string, number]

So if we try to modify the data in a tuple type, TypeScript will throw an error.

const contributionData = getUserContribution(userData);
contributionData[1] = 4000

// Cannot assign to '1' because it is a read-only property.

Summary πŸ’‘

In This article, we covered the basics of tuple types in TypeScript, including their definition, benefits, and practical applications. We also explored an example of how ReactJS hooks utilize tuple types as a return type. By understanding tuple types, you can make your code more organized, readable, and easier to maintain.

That concludes this topic. Thank you for reading!

If you found this article helpful, please consider liking and sharing it with others. If you have any questions, feel free to leave a comment and I will do my best to provide a helpful response.

Resource πŸ“

Connect with me πŸ‘‹

Β