Summary - Tuple
- TypeScript course
- Beginner
- Lesson 19/89
- 4 min
Write labeled coordinate data using tuples.
Tuple summary
A tuple is the type-safe way to group a few related values in a fixed length and order. You make it immutable with readonly, and reach elements by index or destructuring. It fits small but structured data such as labeled coordinate values.
let nokta: readonly [string, number, number] = ["A", 5, 10];
let [etiket, x, y] = nokta;
console.log(etiket); // "A"Tuples are most useful for data that needs a few elements, a clear type order and fixed length.
Practice Labeled coordinate tuple
Define a readonly tuple named nokta with type readonly [string, number, number] and value ["A", 5, 10]. Destructure it into etiket, x and y. Print the value of etiket with console.log.
Starter code
// nokta adında readonly bir tuple tanımla
// üç öğeli: string, number, number
// değer olarak bir etiket ve iki koordinat gir
// nokta'yı etiket, x, y değişkenlerine ayır
// etiket değişkenini yazdırSample solution
let nokta: readonly [string, number, number] = ["A", 5, 10];
let [etiket, x, y] = nokta;
console.log(etiket);Expected output
A
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In <code>let p: readonly [string, number] = ["x", 5]; let [s, n] = p;</code>, what is <code>n</code>?
- 5 Correct answer
- "x"
- [string, number]
- undefined
Explanation: Destructuring assigns the second position to <code>n</code>; the tuple's second element is of type <code>number</code> with value <code>5</code>. Being readonly does not block destructuring.
2 Print the y coordinate
let nokta: readonly [string, number, number] = ["A", 5, 10];
let [etiket, x, y] = nokta;
console.log(____);
let nokta: readonly [string, number, number] = ["A", 5, 10];
let [etiket, x, y] = nokta;
console.log(y);
Explanation: The variable <code>y</code> holds the third position's number (10); <code>etiket</code> and <code>x</code> print other values, while <code>nokta</code> prints the whole tuple.
3 Tuple concepts
| Term | Meaning |
|---|---|
readonly [string, number, number] |
Three-element immutable tuple |
let [a, b, c] = t |
Destructure into three variables |
t[2] |
Access the third element |
Tuple |
Fixed-length ordered array |