DEV Community

Robert Rees
Robert Rees

Posted on

Typescript tuples aren't tuples

I came across some surprising behaviour recently. One of the defining features of tuples is that they can be considered equal if each member of the tuple in the equivalent position is equal.

So the tuple [1, 3] should be equal to the tuple [1,3], but in Typescript they are not because tuples in Typescript are a way of describing the types of heterogeneous arrays (which normally take a single type for all the elements within them).

Arrays are only equal if they are the same reference and there are no special rules for value equality for them in Javascript, which ultimately what we're writing here.

I'm not sure what a better name for what Typescript calls tuples, maybe typed arrays, but the current name does carry some inconvenient expectations for those of us coming from other languages.

Top comments (1)

Collapse
 
e_jarod profile image
EJILANE Jarod

It's normal, ts is a superset of js, so the actual code is just plain js, ts is just here to annotate types.

You don't have tuple operations like in some other languages because tuples don't exists in js, they're just simple arrays.
So when you declare a "tuple" in ts, you should understand it as a "fixed array that will make ts scream if mutated".