CodeBlanks Logo Icon CodeBlanks

What is a tuple?

Learn tuple, fixed-length ordered arrays.

What is a tuple?

A tuple is an array with a fixed length and a specific type at each position. While a regular array holds elements of one type, a tuple lets you place different types side by side in a specific order. The order of types matters: [string, number] and [number, string] are different tuple types.

let kisi: [string, number] = ["Ayşe", 28];
//  two-element, ordered tuple

A tuple is the type-safe way to group a few related values in a single variable.

Tuple type syntax

A tuple type is written as a comma-separated list of types inside square brackets: [type1, type2, ...]. The number of types sets the tuple's length. You can use the string, number and boolean types you have already seen at any position.

let nokta: [number, number] = [3, 4];
let bayrak: [boolean, string] = [true, "aktif"];

A wrong number of elements or a wrong type order produces a compile error.

Practice Name and age tuple

Declare a variable named kisi with type [string, number] and value ["Ayşe", 28]. Print the age value with console.log.

Starter code

index.ts
// kisi adında bir tuple tanımla
// birinci öğe string, ikinci öğe number
// değer olarak bir isim ve bir yaş gir
// kisi'nin ikinci öğesini yazdır

Sample solution

index.ts
let kisi: [string, number] = ["Ayşe", 28];
console.log(kisi[1]);

Expected output

28

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the key feature that distinguishes a tuple from a regular array in TypeScript?

  • It has a fixed length and a specific type at each position Correct answer
  • It can hold only numbers
  • It has no length limit
  • It can hold only strings

Explanation: A tuple's length is fixed by its type list and each position has its own type; a regular array holds elements of one type.

2 Complete the tuple type

Question
let nokta: [number, ____] = [3, 4];
Answer
let nokta: [number, number] = [3, 4];

Explanation: Since the second position is also a number, the tuple type must be <code>[number, number]</code>; it matches the value <code>[3, 4]</code>.

3 Tuple parts

Term Meaning
[string, number] Two-element ordered tuple type
number[] Array where all elements share one type
[boolean, boolean] Two-element boolean tuple
Tuple Fixed-length and ordered array

All lessons in Beginner