Course contentsShow
← TypeScript
Lesson 119 of 1,7963. Basic TypesFree lesson

Tuple Length and Array Methods

Tuples have fixed length property and support array methods, but push/pop can violate type safety without errors.

Tuple Length and Array Methods

What You'll Learn

You'll discover that tuples have a fixed .length property, support array methods like push() and pop(), but these methods can actually break your tuple's type safety without TypeScript warning you.

Understanding Tuple Length

Unlike regular arrays, tuples have a specific, fixed-length type. When you declare a tuple like [string, number], TypeScript knows its .length is exactly 2.

let pair: [string, number] = ["age", 42];
console.log(pair.length); // 2 (TypeScript knows this!)

This length is part of the type itself — TypeScript treats it as a literal number type, not just number.

The Array Methods Problem

Here's the surprising part: tuples are still arrays under the hood, so they inherit all array methods. Unfortunately, methods like push() and pop() can break your tuple's structure:

let person: [string, number] = ["Alice", 30];

person.push("extra"); // TypeScript allows this! 😱
console.log(person); // ["Alice", 30, "extra"]
console.log(person.length); // Now 3, not 2!

Even though you declared a 2-element tuple, push() compiles without error. TypeScript doesn't stop you, but your tuple is no longer the shape you promised.

Why this happens: TypeScript's type system prioritizes flexibility. Array methods are available because tuples are arrays at runtime, but this creates a safety gap.

Key Takeaway

Tuples have a fixed .length type, but array methods like push() and pop() can modify that length at runtime without TypeScript errors — use tuples as immutable data structures to avoid breaking type safety.