Menu
Coddy logo textTech

Readonly Tuples

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 18 of 73.

Just as you can make arrays immutable with the readonly modifier, TypeScript allows you to create readonly tuples that cannot be modified after initialization. This provides the same immutability benefits for structured, fixed-length data.

When you add readonly before a tuple type, TypeScript prevents any changes to the tuple's elements.

This means you cannot reassign values at specific positions or use methods that would modify the tuple's contents:

let point: readonly [number, number] = [10, 20];
let coordinates: readonly [string, number, number] = ["A", 5, 15];

The readonly modifier is particularly valuable for tuples because they often represent important structured data like coordinates, RGB color values, or database records that shouldn't change once created.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Create a readonly tuple named startPointthat represents a 2D point with two numbers (x and y coordinates). Initialize it with the values 0 and 0.

Create another readonly tuple named colorRGB that represents an RGB color value with three numbers (red, green, blue). Initialize it with the values 255, 128, and 64.

Create a third readonly tuple named userRecord that holds a number (user ID), a string (username), and a boolean (active status). Initialize it with the values 42, "admin", and true.

Print all three readonly tuples to the console on separate lines in the order they were created.

Cheat sheet

Create readonly tuples using the readonly modifier before the tuple type to prevent modifications after initialization:

let point: readonly [number, number] = [10, 20];
let coordinates: readonly [string, number, number] = ["A", 5, 15];

Readonly tuples are useful for structured data like coordinates, RGB values, or database records that shouldn't change once created.

Try it yourself

// TODO: Write your code here
// Create the readonly tuples as described in the challenge

// Print all three tuples
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To TypeScript