🤔 ️ requirements

Implement a type UnionToTuple that converts a union into a tuple.

Since a union is an unordered structure, a tuple is an ordered structure. So in this challenge, the order of elements in a tuple can be returned in any order. But not for their union type.

UnionToTuple<1>           // [1], and correct

UnionToTuple<'any' | 'a'> // ['any','a'], and correct
Copy the code

or

UnionToTuple<'any' | 'a'> // ['a','any'], and correct
Copy the code

He shouldn’t be all the right types of union types

UnionToTuple<'any' | 'a'> // ['a','any'] | ['any','a'], which is incorrect
Copy the code

Types can be omitted, for example.

Equal<UnionToTuple<any | 'a'>,UnionToTuple<any>>  // will always be a true

Equal<UnionToTuple<unknown | 'a'>,UnionToTuple<unknown>> // will always be a true

Equal<UnionToTuple<never | 'a'>,UnionToTuple<'a'>>  // will always be a true

Equal<UnionToTuple<'a' | 'a' | 'a'>, UnionToTuple<'a'>>// will always be a true
Copy the code

📖 knowledge

🔗 Knowledge links

  1. UnionToIntersection
type UnionToIntersection = (T extends any ? (args: T) = > any: never) extends (args: infer R) => any ? R : never; In order to UnionToIntersection <'a' | 'b'> as an example. * Textends anyBy using theextends[distribute] (HTTPS:/ / www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types) features. Because any type extends any, into ` ((args: 'a') = > any | (args: 'b') = > any) extends (args: infer R) = > any? : R : never; `* [If inextends"Uses infer. For a given infer type variable V, if there are candidate types that can be inferred from covariant positions, the type of V is the combination of those candidate types. Conversely, if there are candidate types that are inferred from contravariant positions, then the type of V is the crossover type of those candidate types. Otherwise V is of typenever. ] (https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types)* According to the above principle, infer R is in the inverting position, so`infer R`Is the union type of the candidate types`'a' & 'b'`
Copy the code

For details, see the article I wrote last time juejin.cn/post/697624…

  1. How can I tell if a type is Never?

    • Refer to link 1: github.com/type-challe…
    • Reference link 2: github.com/microsoft/T…
  2. Function overloading

    • In TS, the union type of multiple function types is understood as an overload.
  3. Getting the return type of an overloaded type gets the type of the last item

type Override<T> = UnionToIntersection<(T extends any ? (arg: T) = > T : never) >type A = Override<'a' | 'b'> //(arg: 'a') => 'a' & (arg: 'b') => b

declare const fn : A ; // Define A function fn of type A

fn('a') // no error

fn('b') // no error

type R = ReturnType<A>; // Get the last item of type A of type 'b'
Copy the code

😢 Questions & Answers

  1. Union to Tuple
  2. answer