This Typescript Behavior Will Make You Cringe
A weird way to infer Tuples in Typescript
So today I was browsing through X and I came across this crazy post from Matt Pocock:
Just when I thought I understood Typescript, I was hit with this brand-new trick that made no sense to me.
So what does this trick do?
As Matt's post points out, the trick is to add a | []
to the generic parameter TRoutes extends string[]
, and suddenly you go from inferring this:
string[]
to this:
[string, string, string]
The code above is a type definition for a Tuple, and weirdly enough, we need to use the | []
syntax to achieve something like this for tuples of variable length.
When is it useful?
It turns out there is a creative application for this Typescript quirk.
By creating a type Tuple = unknown[] | []
we can use this as a "caster" with the satisfies
keyword; let me explain using the code below:
Here we use satisfies Tuple
to cast each key-value pair to our Tuple type.
So instead of the final output type being (string | number)[][]
, we know it will be [string, number][]
, which is more accurate and will create more consistent code.
Why not `as const`?
We could technically replace the satisfies Tuple
cast with as const
, but this comes with a caveat.
When you apply as const
, the resulting type of mapped
becomes:
(readonly [string,number])[]
Since the key-value pairs are marked as readonly
, this means typescript will get mad at you if you try to edit the key-value pairs later in the program.
Wrapping up
This typescript trick is weird, don't get me wrong, but I find it cool that such a trick can have realistic use cases.
Typescript is full of little quirks like this, and I will make it my mission to cover as many of them as possible for you guys.
I hope you enjoyed this article, see you in the next one. 🫡
If you enjoyed this article, please make sure to Subscribe, Clap, Comment and Connect with me today! 🌐