问题
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