Tuple usage
- TypeScript course
- Beginner
- Lesson 17/89
- 4 min
Learn to create tuples and access their elements.
Accessing tuple elements
You access tuple elements by index just like arrays: t[0] returns the first element and t[1] the second. TypeScript knows the exact type at each index, so t[0] on a [string, number] tuple is of type string.
let p: [string, number] = ["x", 5];
console.log(p[0]); // "x"
console.log(p[1]); // 5Because the index type is correct, the compiler asks for no extra conversion.
Tuple destructuring
You use destructuring to pull a tuple's elements into separate variables: let [a, b] = t. This assigns the first element to a and the second to b. Each variable receives the type of its position.
let p: [string, number] = ["x", 5];
let [ad, yas] = p;
// ad: string, yas: numberDestructuring is the short way to unfold a tuple into named variables in one line.
Practice Name and price with destructuring
Declare a tuple variable named urun with type [string, number] and value ["kalem", 15]. Destructure it into ad and fiyat. Print the value of ad with console.log.
Starter code
// urun adında bir tuple tanımla
// birinci öğe string, ikinci öğe number
// değer olarak bir ürün adı ve bir fiyat gir
// urun'ü ad ve fiyat değişkenlerine ayır
// ad değişkenini yazdırSample solution
let urun: [string, number] = ["kalem", 15];
let [ad, fiyat] = urun;
console.log(ad);Expected output
kalem
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In <code>let p: [string, number] = ["x", 5]</code>, what does <code>p[1]</code> return?
- true
- 5 Correct answer
- undefined
- "x"
Explanation: The second position is of type <code>number</code> with value <code>5</code>; <code>p[0]</code> would return <code>"x"</code>.
2 Split the tuple with destructuring
let bilgi: [string, number] = ["saat", 12];
let [birim, deger] = ____;
let bilgi: [string, number] = ["saat", 12];
let [birim, deger] = bilgi;
Explanation: The source of destructuring is the tuple variable itself; <code>bilgi[0]</code> returns only a <code>string</code> and cannot be unpacked into two variables.
3 Access and destructuring
| Term | Meaning |
|---|---|
t[0] |
Access the first element |
t[1] |
Access the second element |
let [a, b] = t |
Unfold the tuple into two variables |
Destructuring |
Split tuple elements into named variables |