AI Hints
Home›TypeScript Tutorial›Basic Types
TypeScript · Lesson 9 of 120

Tuples

Fixed positions.

⏱ 2 min read▶ Video at 7:30🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Sometimes a list has a fixed shape. Like a store's name, then its number of bikes. A tuple fixes how many items there are, and the type at each position.

Tuples
From the video: Tuples
  • Fixed length
  • A type per position
  • Tuples

A tuple

Stock is a tuple, a string, then a number. Destructuring pulls both values out, into named variables. Run it.

app.tstypescript
const stock: [string, number] = ["Leeds", 12];

const [store, bikes] = stock;
console.log(`${store} has ${bikes} bikes`);
Output
Leeds has 12 bikes

Wrong order

Here the values are swapped, number first. Run it. Each position has its own type, so both are wrong.

app.tstypescript
const stock: [string, number] = [12, "Leeds"];
Output
app.ts line 1: Type 'number' is not assignable to type 'string'.
app.ts line 1: Type 'string' is not assignable to type 'number'.

Summary

Tuples fix the length, and the type at each position. Next, the escape hatches, any and unknown.

Key takeaways
  • [string, number]
  • Destructuring
  • Order matters
Next up: any and unknown — the escape hatches