【发布时间】:2020-08-24 21:03:48
【问题描述】:
我的问题是参考这篇文章
Transform union type to intersection type
每当我将联合转换为交集时,我都会失去联合类型,这是我为解决这个问题而编写的一些代码
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'];
所以我对代码不是 100% 有信心,重新考虑一下会很有帮助。 当这样的事情会失败以及如何解决同样的事情时,我很好奇。
提前致谢。
【问题讨论】:
-
我不明白这一点。给定
A和B类型,UnionToIntersection<A | B>按预期返回A & B。没有never,没有过度工程。可能是我没有得到你想要得到的东西,抱歉。 -
'AbIntersection' 中的 'unionType' 类型返回为从不返回,后者不是这种情况......
-
never是'A' & 'B'的正确交集。你认为结果应该是什么,为什么?
标签: typescript typescript-typings