Typescript Union To Intersection returns values as never

核能气质少年 提交于 2021-02-08 05:25:11

问题


My question is with reference to this post

Transform union type to intersection type

Whenever i convert a union To Intersection i loose the union type, here is some code i wrote to get around the issue

type SomeUnion = 'A' | 'B';


type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never

type UnionToInterSectionWoNever<T> = {
  [K in keyof UnionToIntersection<T>]: UnionToIntersection<T>[K] extends never ? T[K] : UnionToIntersection<T>[K]
};


type UnionDistribution<T> = T extends SomeUnion ?
  { unionType: T } & (
    T extends 'A' ? { aProp1: string, aProp2: number } :
    T extends 'B' ? { bProp1: string } : never) :
  never;

type ABUnion = UnionDistribution<SomeUnion>;

type ABInterSection = UnionToIntersection<ABUnion>;

type ABInterSectionWoNever = UnionToInterSectionWoNever<ABUnion>;

// This in infered as never;
type ABInterSectionUnionType = ABInterSection['unionType'];

// This in inferred as 'A' | 'B'
type ABInterSectionWoNeverUnionType = ABInterSectionWoNever['unionType'];

So i am not 100% confident of the code, it would be really helpful to have a second thought on the same. I'm curios when something like this will fail and how to resolve the same.

Thanks in Advance.


回答1:


You get never because TypeScript can not represent type as 'A' & 'B'.

Check this out:

type test = {
  foo: 'bar',
} & {
  foo: 'baz',
} // never

type test2 = 'A' & 'B' // never

It was found in a TS Challenge issue occasionally.



来源:https://stackoverflow.com/questions/61693847/typescript-union-to-intersection-returns-values-as-never

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!