我的问题是关于这篇文章的
每当我将一个联合类型转换为交叉类型时,就会失去联合类型,这里是我编写的一些代码,以解决这个问题。
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'];
我对这段代码不太有信心,希望能得到第二个人的看法。我很想知道像这样的代码会在什么情况下失败以及如何解决它。
谢谢提前。
A
和B
类型,UnionToIntersection<A | B>
返回预期的A & B
。没有never
,也没有过度设计。可能是我没有理解你想要表达的意思,抱歉。 - VRoxa'A' & 'B'
的正确交集。您认为结果还应该是什么,为什么? - kaya3