TypeScript Tuple

TypeScript is a superset of JavaScript that provides optional static typing, making it easier to write complex code. One of the features that TypeScript provides is the ability to define tuples. A tuple is a collection of values of different types. In this lesson, we will go over what TypeScript tuples are, how they work, and how to use them with code examples.

What is a Tuple in TypeScript?

In TypeScript, a tuple is a fixed-length array that can contain elements of different types. Unlike arrays, tuples have a specific order and type for each element in the array.

Here is an example of a tuple in TypeScript:

let tuple: [string, number];
tuple = ['hello', 42];

In this example, we declare a variable called tuple of type [string, number]. We then assign it an array containing a string and a number. The order of the elements in the array must match the order of the types in the tuple.

You can also use type aliases to make tuples easier to work with:

type Point = [number, number];

let point: Point = [10, 20];

In this example, we define a type alias called Point that is a tuple of two numbers. We then declare a variable called point of type Point and assign it a tuple of two numbers.

How to use a Tuple in TypeScript

Once you have defined a tuple, you can use it in your code like this:

function printTuple(tuple: [string, number]) {
  console.log(`The string is ${tuple[0]} and the number is ${tuple[1]}`);
}

printTuple(['hello', 42]); // Output: The string is hello and the number is 42

In this example, we define a function called printTuple that takes a tuple of type [string, number] as an argument. We then use the tuple elements to print out a message to the console.

You can also use destructuring to extract the elements of a tuple into separate variables:

let tuple: [string, number] = ['hello', 42];
let [str, num] = tuple;

console.log(`The string is ${str} and the number is ${num}`); // Output: The string is hello and the number is 42

In this example, we declare a variable called tuple of type [string, number] and assign it a tuple of a string and a number. We then use destructuring to extract the string and number elements into separate variables called str and num. We then print out a message to the console using the extracted variables.

Conclusion

In conclusion, tuples are a powerful feature of TypeScript that make it easier to work with fixed-length arrays that contain elements of different types. They help make your code more readable, maintainable, and less error-prone. With tuples, you can define a fixed-length array that contains elements of different types and use them in your code. We hope this lesson has helped you understand what TypeScript tuples are and how to use them.