Skip to main content

Union to Intersection

introduction#

Implement the advanced util type UnionToIntersection<U>

For example

ts
type I = Union2Intersection<'foo' | 42 | true>; // expected to be 'foo' & 42 & true
ts
type I = Union2Intersection<'foo' | 42 | true>; // expected to be 'foo' & 42 & true
View on GitHub

start point#

ts
/* _____________ Your Code Here _____________ */
type UnionToIntersection<U> = any
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<UnionToIntersection<'foo' | 42 | true>, 'foo' & 42 & true>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<UnionToIntersection<(() => 'foo') | ((i: 42) => true)>, (() => 'foo') & ((i: 42) => true)>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
Try
ts
/* _____________ Your Code Here _____________ */
type UnionToIntersection<U> = any
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<UnionToIntersection<'foo' | 42 | true>, 'foo' & 42 & true>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<UnionToIntersection<(() => 'foo') | ((i: 42) => true)>, (() => 'foo') & ((i: 42) => true)>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
Try
take the challenge

my solutions#

Spoiler warning // Click to reveal answer
ts
type UnionToIntersection<U> = (U extends any ? (arg: U) => any : never) extends (
arg: infer I
) => void
? I
: never;
Try
ts
type UnionToIntersection<U> = (U extends any ? (arg: U) => any : never) extends (
arg: infer I
) => void
? I
: never;
Try
view more solutions