Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Union To Intersection returns values as never

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.

like image 859
Amol Gupta Avatar asked Jul 20 '26 11:07

Amol Gupta


1 Answers

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.

like image 88
avdotion Avatar answered Jul 23 '26 05:07

avdotion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!