Calculate all permutations of union type in TypeScript
Today we discuss Permutation
This is more synthetic example which can be hardly used in production. I didn't know about it beforehand.
Anyway let's try to solve it 🚀
Iterate over union type
Using unknown
, any
or never
we can distribute union type:
But if we try this one, we will get an error Type instantiation is excessively deep and possibly infinite
.
Somehow we need to store the union element which we currently put into the tuple, and then iterate over the rest elements. For this reason let's add another Generic type variable K
:
Now we face never
🧐 for all the examples https://tsplay.dev/wj5EbW
Check if type is never or not
We have never
because at the last step we have nothing to iterate over in a union type. Let's have a short example:
So for never
we should return empty array to fix this problem.
To prevent future errors, we shouldn't use T extends never
as this distributes union type the same way as for unknown
and any
. So it's not what we look for.
However, if we wrap T
and never
in a tuple and use [T] extends [never]
, it will actually check for never
. Let's include it in the solution:
Looks overloaded but not that hard, right? 😊
All together
Let's recap ⬇️
- We apply Distributive Conditional Types for
K
which allows us to include elements into a tuple step by step - With
K
we exclude just added element from next steps usingExclude<T, K>
- Last iteration where there is nothing in union type we return empty tuple. We do this with condition
[T] extends [never]
Please check the solution with test cases: https://tsplay.dev/weexew
Have a wonderful week ahead 🚀
typescript