0
0
Typescriptprogramming~5 mins

Tuple type definition in Typescript

Choose your learning style9 modes available
Introduction

A tuple lets you store a fixed number of items with different types together. It helps keep related data organized and clear.

When you want to group a few values of different types, like a name and age.
When a function returns multiple values of different types.
When you want to represent a pair or triple of related data, like coordinates (x, y).
When you want to ensure the order and type of elements in a small collection.
When you want to pass a fixed set of mixed-type values as one variable.
Syntax
Typescript
let variableName: [type1, type2, ...];

The number of types inside the square brackets [] sets the tuple size.

Each position has a fixed type, so order matters.

Examples
This tuple stores a string and a number, like a name and age.
Typescript
let person: [string, number];
person = ["Alice", 30];
This tuple stores two numbers representing coordinates.
Typescript
let point: [number, number];
point = [10, 20];
This tuple stores a status code, message, and success flag.
Typescript
let response: [number, string, boolean];
response = [200, "OK", true];
Sample Program

This program defines a function that returns a tuple with a name and age. It then prints them.

Typescript
function getUserInfo(): [string, number] {
  return ["Bob", 25];
}

const userInfo = getUserInfo();
console.log(`Name: ${userInfo[0]}, Age: ${userInfo[1]}`);
OutputSuccess
Important Notes

You cannot add or remove elements from a tuple; its size is fixed.

Access tuple elements by their position, like array indexes.

Tuples help catch mistakes by enforcing types and order.

Summary

Tuples store a fixed number of values with specific types in order.

Use tuples to group related but different types of data together.

They help keep your code clear and safe by checking types and positions.