Typescript Foundations / Basic Types

Tuples in Typescript

👉 A tuple is a fixed-length array where each element has a specific type and position.

Unlike regular arrays (where all elements are of the same type), tuples let you define different types at different positions.


⚡ Syntax

let tupleName: [Type1, Type2, ..., TypeN] = [value1, value2, ..., valueN];

✍ Example

let user: [string, number] = ["Alice", 30];

✅ This tuple:

  • The first element is a string

  • The second element is a number

console.log(user[0]);  // "Alice"
console.log(user[1]);  // 30

❌ If you try:

user = [30, "Alice"];  // Error: types are in the wrong order

🚀 Common use cases

  • Represent a pair of values (e.g. coordinates, key-value pairs)

  • Return multiple values from a function

  • Represent structured data without creating a full interface


⚙ Tuples with optional elements

let point: [number, number, number?] = [10, 20];

✅ The third value is optional.


⚡ Readonly tuples

const pair: readonly [string, number] = ["id", 101];
// pair[0] = "newId"; ❌ Error: Cannot assign to readonly element

⚡ Tuple with rest elements

let rgb: [number, number, number, ...string[]] = [255, 0, 0, "red", "bright"];

✅ First 3 are numbers, then any number of strings.


💡 Accessing elements

Elements have their specific types:

let data: [string, boolean] = ["loaded", true];

let status: string = data[0];
let flag: boolean = data[1];

Trying to access beyond the defined length:

console.log(data[2]);  // TS error or `undefined` at runtime

⚠ Tuple vs array

Feature

Tuple

Array

Length

Fixed (or known optional parts)

Variable

Types

Can vary by position

Usually all elements same type

Example

[string, number]

string[]


✨ Summary

Tuple type

Example

[string, number]

["Alice", 30]

[number, number, number?]

[10, 20]

[boolean, ...string[]]

[true, "a", "b"]