Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

Tuples in TypeScript

Learn how to create tuples, specify element types, access and update tuple values, use named tuple elements, and work with optional and readonly tuples in TypeScript.

Simple Explanation: A tuple is an array type that describes the expected types of elements at specific positions. For example, a tuple can store a student's name as a string and age as a number.

What Is a Tuple?

A tuple is useful when a collection contains a known number of elements whose positions have specific types. Unlike a normal array, a tuple can describe a different type for each position.

For example, a student record can contain a name, age, and pass status in a single tuple.

  • Tuple types specify the expected element types and their positions.
  • Tuple elements are accessed using indexes, starting from 0.
  • TypeScript checks assignments and access against the declared tuple type.
  • Tuples can support optional elements and rest elements.
  • Readonly tuples prevent modification through the readonly reference at compile time.

Tuple Workflow

Follow these steps to understand how a tuple is declared and used in a TypeScript program.

📝
Step 1
Declare Tuple

Specify the expected type of each position.

→
📦
Step 2
Assign Values

Supply values in the expected order.

→
🔍
Step 3
Access Elements

Read or update tuple elements by index.

→
✅
Step 4
Use Data

Process values in your application.

Visual Example: Student Tuple
Index 0
"Priya"

string

Index 1
22

number

Index 2
true

boolean

Tuple Type: [string, number, boolean]

1. Declaring a Tuple in TypeScript

A tuple type is declared by specifying the element types inside square brackets.

Syntax

let tupleName: [type1, type2] = [value1, value2];

Example

let student: [string, number] = ["Priya", 22];

console.log(student);

Expected Output

[ 'Priya', 22 ]

Explanation

  • The first position expects a string.
  • The second position expects a number.
  • TypeScript checks that the assigned values match the declared tuple type.

2. Accessing Tuple Elements

Tuple elements can be accessed using their index positions, just like array elements.

Example

let student: [string, number, boolean] = [
    "Rahul",
    21,
    true
];

console.log(student[0]);
console.log(student[1]);
console.log(student[2]);

Expected Output

Rahul
21
true

Explanation

  • student[0] accesses the name.
  • student[1] accesses the age.
  • student[2] accesses the boolean value.

3. Updating Tuple Elements

Tuple elements can be updated when the new value matches the type expected at that position.

Example

let student: [string, number] = ["Priya", 22];

student[0] = "Neha";
student[1] = 23;

console.log(student);

Expected Output

[ 'Neha', 23 ]

Explanation

The name and age are updated using their indexes. The tuple type still requires a string at index 0 and a number at index 1.

4. Tuple with Multiple Data Types

A tuple can contain different data types at different positions. This is useful for representing a compact record of related values.

Example

let employee: [number, string, boolean] = [
    101,
    "Amit",
    true
];

console.log("Employee ID:", employee[0]);
console.log("Employee Name:", employee[1]);
console.log("Is Active:", employee[2]);

Expected Output

Employee ID: 101
Employee Name: Amit
Is Active: true

Explanation

  • Index 0 stores a numeric employee ID.
  • Index 1 stores the employee name.
  • Index 2 stores the employee's active status.

5. Named Tuple Elements

TypeScript allows names to be added to tuple elements to make their meaning clearer. These names improve readability but do not change the runtime structure.

Example

let student: [name: string, age: number] = [
    "Priya",
    22
];

console.log("Name:", student[0]);
console.log("Age:", student[1]);

Expected Output

Name: Priya
Age: 22

Explanation

The names name and age describe the meaning of the tuple positions. The values are still accessed using indexes.

6. Optional Tuple Elements

A question mark after a tuple element indicates that the element is optional. It may be omitted from the tuple value.

Example

let student1: [string, number?] = ["Rahul"];
let student2: [string, number?] = ["Priya", 22];

console.log(student1);
console.log(student2);

Expected Output

[ 'Rahul' ]
[ 'Priya', 22 ]

Explanation

  • The name is required.
  • The age is optional.
  • Both tuple values are valid according to the declared tuple type.

7. Readonly Tuples

A readonly tuple prevents its elements from being changed through the readonly reference. This is useful when tuple values should only be read.

Example

const student: readonly [string, number] = [
    "Priya",
    22
];

console.log(student[0]);
console.log(student[1]);

Expected Output

Priya
22

Invalid Operations

// TypeScript compile-time errors:
student[0] = "Rahul";
student.push("New Value");
Remember: Readonly restrictions are enforced by TypeScript's type checker. They do not automatically freeze the underlying JavaScript array at runtime.

8. Rest Elements in Tuples

A tuple can contain a rest element to represent zero or more additional elements of a particular type. This is useful when some positions are fixed and the remaining values are variable in number.

Example

let studentMarks: [string, ...number[]] = [
    "Rahul",
    75,
    80,
    90
];

console.log("Student:", studentMarks[0]);
console.log("Marks:", studentMarks.slice(1));

Expected Output

Student: Rahul
Marks: [ 75, 80, 90 ]

Explanation

  • The first element must be a string.
  • The remaining elements can be numbers.
  • The number of marks can vary.

9. Tuples vs Arrays

Tuples and arrays are both ordered collections, but they describe element types differently.

Feature Array Tuple
Element types Usually described by one element type. Can specify a type for each position.
Example type string[] [string, number]
Typical values ["Java", "Python"] ["Priya", 22]
Typical use Lists of similar values. Records with different types at known positions.
Number of elements Can vary. Defined by the tuple type, with optional and rest elements available when required.

10. Practical Example: CIIT Student Record

Let's create a tuple to store a student's name, age, and course, and then display each value.

Example

let student: [name: string, age: number, course: string] = [
    "Priya",
    22,
    "Dot Net Full Stack"
];

console.log("Student Name:", student[0]);
console.log("Age:", student[1]);
console.log("Course:", student[2]);

Expected Output

Student Name: Priya
Age: 22
Course: Dot Net Full Stack

Explanation

  • The tuple stores three related pieces of information.
  • The name and course are strings.
  • The age is a number.
  • Each value is accessed by its position in the tuple.

Common Mistakes

  • Assigning a value that does not match the type expected at that tuple position.
  • Accessing a tuple element using the wrong index.
  • Adding additional elements to a fixed-length tuple without declaring an appropriate tuple type.
  • Modifying a readonly tuple.
  • Forgetting that optional tuple elements may be absent.
Remember: Tuple types describe the expected type of each position. Choose the tuple structure according to the data you need to represent.

Practice Task

Write TypeScript programs to complete the following tasks.

  • Create a tuple containing a student's name and age.
  • Create an employee tuple containing ID, name, and active status.
  • Update a tuple element with another value of the correct type.
  • Create a tuple with an optional age element.
  • Create a readonly tuple and identify which operations TypeScript rejects.
  • Create a tuple with a name followed by multiple numeric marks using a rest element.
Challenge: Use a tuple to store a student's name, course, and marks, then display each value.

Summary

In this lesson, we learned how to declare tuples, specify element types, access and update tuple values, use named elements, declare optional and readonly tuples, and work with rest elements. Tuples are useful when each position in a collection has a specific meaning and expected type.