readonly tuple
- TypeScript course
- Beginner
- Lesson 18/89
- 4 min
Learn immutable tuples with readonly tuple.
readonly tuple
To prevent a tuple's elements from being modified later, you put the readonly keyword in front of the type: readonly [string, number]. You can read elements of such a tuple but you cannot assign to them.
let t: readonly [string, number] = ["a", 1];
console.log(t[0]); // "a"
t[0] = "b"; // compile errorA readonly tuple is used when data must stay unchanged after creation.
When to use a readonly tuple
A readonly tuple fits data that must not change later, such as configuration values, fixed coordinates or protected return data from a function. Like readonly arrays, accidental modification is blocked at compile time.
let ayar: readonly [string, boolean] = ["debug", true];
console.log(ayar[0]); // "debug"A tuple's length and order are already fixed; readonly also locks content changes.
Practice Configuration with a readonly tuple
Define a readonly tuple named config with type readonly [string, number] and value ["port", 3000]. Print the second element with console.log.
Starter code
// config adında readonly bir tuple tanımla
// birinci öğe string, ikinci öğe number
// değer olarak bir ayar adı ve bir sayı gir
// config'in ikinci öğesini yazdırSample solution
let config: readonly [string, number] = ["port", 3000];
console.log(config[1]);Expected output
3000
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which code produces a TypeScript compile error?
- let t: readonly [string] = ["x"]; console.log(t[0]);
- let t: [string, number] = ["a", 1]; console.log(t.length);
- let t: [number, number] = [1, 2]; t[0] = 5;
- let t: readonly [number, number] = [1, 2]; t[0] = 5; Correct answer
Explanation: A <code>readonly</code> tuple does not allow element assignment, so <code>t[0] = 5</code> gives a compile error. The other options either lack <code>readonly</code> or only read.
2 Complete the readonly tuple type
let ayar: readonly [string, ____] = ["debug", true];
let ayar: readonly [string, boolean] = ["debug", true];
Explanation: Because the second position holds <code>true</code>, its type must be <code>boolean</code>; <code>readonly [string, boolean]</code> is the correct completion.
3 readonly and mutation
| Term | Meaning |
|---|---|
readonly [string, number] |
Immutable tuple type |
t[0] = "x" |
Element assignment (mutation) |
readonly tuple |
Elements cannot be reassigned later |
readonly number[] |
Immutable array type |