Open utterances-bot opened 3 years ago
My two cents to enhance your great explaination. You put []
around the T
type parameter to stop the distribution over union from taking place...you don't want it in that point. You need it right after.
You are right, thanks for clarification! Recently, I've figured it out myself by going through updated TypeScript handbook. For others to read, here is a link to how to disable distributivity over unions.
There is a small footnote:
Typically, distributivity is the desired behavior. To avoid that behavior, you can surround each side of the
extends
keyword with square brackets.
I think final solution is overcomplicated. I've used your idea (thx for project :fire:) to make up this variant. I found it more clear:
// We still need a copy of source type to have source and distributed types
type Permutation<T, C = T> =
// Here we checks that source type is not empty
[T] extends [never]
? []
// We don't care about type, just need to distribute union
: T extends unknown
// Exclude current type from source union
? [T, ...Permutation<Exclude<C, T>>]
: never
Cool project, thanks for your contribution!
BTW, I found a detailed explanation in the original type-challenges repo: https://github.com/type-challenges/type-challenges/issues/614
Thanks for your contribution! I wrote a Chinese detailed explanatation for anyone need it: https://juejin.cn/post/7165170011282079751
Permutation
This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.
https://ghaiklor.github.io/type-challenges-solutions/en/medium-permutation.html