0
0
Typescriptprogramming~5 mins

Tuple with fixed length and types in Typescript

Choose your learning style9 modes available
Introduction

A tuple lets you store a fixed number of values, each with a specific type. It helps keep data organized and safe.

When you want to group a few related values of different types together, like a person's name and age.
When you need to return multiple values from a function with known types and order.
When you want to represent a fixed structure, like a coordinate with x and y numbers.
When you want to ensure the data always has the same length and types in the same order.
Syntax
Typescript
let variableName: [type1, type2, type3];

// Example:
let person: [string, number];

Each position in the tuple has a fixed type.

The length of the tuple is fixed by the number of types you list.

Examples
A tuple with two numbers representing a point's x and y coordinates.
Typescript
let point: [number, number];
point = [10, 20];
A tuple with a string, number, and boolean for a user's name, age, and active status.
Typescript
let user: [string, number, boolean];
user = ['Alice', 30, true];
A tuple with zero elements, always empty.
Typescript
let emptyTuple: [];
emptyTuple = [];
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: [string, number] = getUserInfo();
console.log(`Name: ${userInfo[0]}, Age: ${userInfo[1]}`);
OutputSuccess
Important Notes

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

Access tuple elements by their position, starting at 0.

TypeScript will check the types and order to prevent mistakes.

Summary

Tuples store a fixed number of values with specific types.

They help keep related data organized and type-safe.

Use tuples when you know the exact number and types of elements.