[Typescript] 91. Hard - Union to Intersection

Implement the advanced util type UnionToIntersection<U>

For example

type I = Union2Intersection<'foo' | 42 | true> // expected to be 'foo' & 42 & true

 

https://www.cnblogs.com/Answer1215/p/16874524.html

/* _____________ Your Code Here _____________ */

type UnionToIntersection<U> = (U extends any ? (x: U) => any: never) extends 
  (x: infer R) => any ? R: never;



/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<UnionToIntersection<'foo' | 42 | true>, 'foo' & 42 & true>>,
  Expect<Equal<UnionToIntersection<(() => 'foo') | ((i: 42) => true)>, (() => 'foo') & ((i: 42) => true)>>,
]

 

posted @ 2022-11-09 17:22  Zhentiw  阅读(26)  评论(0编辑  收藏  举报