DEV Community

Cover image for Did You Know? Tuples Loophole in Typescript
Sonu kumar
Sonu kumar

Posted on

Did You Know? Tuples Loophole in Typescript

As TypeScript developers, we use Tuples when we want to define an array with a fixed number of elements and specific types. It’s a great way to ensure data integrity—or so we think.

Take a look at this behavior:

// Defining a Tuple
let emplCode: [string, number] = ['Alice', 1101]; 

// ❌ Assignment Error: TypeScript catches this!
emplCode = ['Bob', 1102, 'Admin']; 

// ✅ Mutation "Success": TypeScript allows this?!
emplCode.push(6); 

console.log(emplCode); // Output: ["Alice", 1101, 6]
Enter fullscreen mode Exit fullscreen mode

The "Why" Behind the Quirk

Why does TypeScript block an assignment but allow a .push()?

Tuples in TypeScript are compiled into standard JavaScript Arrays. While the TypeScript compiler is strict about the initial assignment and index access, it inherits methods like .push(), .pop(), and .splice() from the Array.prototype. These methods are dynamic by nature, and TypeScript (by default) doesn't override them for tuples.

The Risk ⚠️

This creates a "Type-Runtime Gap." If you push an element into a tuple, your array length changes at runtime, but TypeScript’s type-checker still "thinks" the tuple only has two elements. If you try to access emplCode[2], you’ll get a compilation error even though the data exists!

The Professional Solution

If you want to enforce a truly fixed-size structure and prevent accidental mutations,
Use the readonly modifier:

let emplCode: readonly [string, number] = ['Alice', 1101];

emplCode.push(6); // ❌ Property 'push' does not exist on type 'readonly [string, number]'.
Enter fullscreen mode Exit fullscreen mode

The Takeaway:

Never assume a Tuple is immutable unless you explicitly tell TypeScript to make it so.

Quick Quiz for the Devs: 👇

When handling fixed pairs of data (like coordinates or Key-Value pairs), do you prefer using Tuples or do you stick to Interface-based Objects?

Let’s debate the pros and cons in the comments! 🚀

Top comments (0)