ghaiklor / type-challenges-solutions

Solutions for the collection of TypeScript type challenges with explanations
https://ghaiklor.github.io/type-challenges-solutions/
Creative Commons Attribution 4.0 International
470 stars 56 forks source link

type-challenges-solutions/en/medium-permutation #76

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

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

jfet97 commented 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.

ghaiklor commented 3 years ago

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.

ilmpc commented 2 years ago

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
nmonastyrskyi commented 2 years ago

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

zhaoyao91 commented 1 year ago

Thanks for your contribution! I wrote a Chinese detailed explanatation for anyone need it: https://juejin.cn/post/7165170011282079751