Menu
Coddy logo textTech

Declaring and Accessing Tuples

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 16 of 73.

The syntax for creating a tuple is straightforward: you specify the types of each element in square brackets, in the exact order they should appear.

To declare a tuple, you use the format [Type1, Type2, Type3] where each type corresponds to a specific position:

let productInfo: [string, number] = ["Laptop", 999];
let coordinates: [number, number] = [10, 20];
let userRecord: [number, string, boolean] = [1, "Alice", true];

Accessing tuple elements works exactly like accessing array elements using index notation. TypeScript knows the exact type at each position, so you get full type safety:

let product: [string, number] = ["Phone", 599];
console.log(product[0]); // "Phone" (TypeScript knows this is a string)
console.log(product[1]); // 599 (TypeScript knows this is a number)

The key advantage is that TypeScript enforces both the correct type and the correct position. If you try to access product[0].toFixed(), TypeScript will catch the error because it knows the first element is a string, not a number.

challenge icon

Challenge

Easy

Create a tuple named productInfo that holds a string (product name) followed by a number (price). Initialize it with the product name "Gaming Mouse" and the price 79.

Then create another tuple named coordinates that holds two numbers representing x and y positions. Initialize it with the values 15 and 25.

Access and print the product name from the productInfo tuple.

Access and print the price from the productInfo tuple.

Access and print the x coordinate from the coordinates tuple.

Access and print the y coordinate from the coordinates tuple.

Print each value on a separate line in the order specified above.

Try it yourself

// TODO: Write your code here
// Create the productInfo tuple with product name and price
// Create the coordinates tuple with x and y positions
// Access and print each value as specified
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To TypeScript