Menu

Post image 1
Post image 2
1 / 2
0

Did You Know? Tuples Loophole in Typescript

DEV Community·Sonu kumar·20 days ago
#4ZQRC2wX
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More