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 🚀
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
Now we face
never 🧐 for all the examples https://tsplay.dev/wj5EbW
never because at the last step we have nothing to iterate over in a union type. Let's have a short example:
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
any. So it's not what we look for.
However, if we wrap
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? 😊
Let's recap ⬇️
- We apply Distributive Conditional Types for
Kwhich allows us to include elements into a tuple step by step
Kwe exclude just added element from next steps using
- 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