TypeScript的联合类型转交叉类型返回值为never。

3

我的问题是关于这篇文章的

将联合类型转换为交叉类型

每当我将一个联合类型转换为交叉类型时,就会失去联合类型,这里是我编写的一些代码,以解决这个问题。

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'];

我对这段代码不太有信心,希望能得到第二个人的看法。我很想知道像这样的代码会在什么情况下失败以及如何解决它。

谢谢提前。


我不明白重点在哪里。给定 AB 类型,UnionToIntersection<A | B> 返回预期的 A & B。没有 never,也没有过度设计。可能是我没有理解你想要表达的意思,抱歉。 - VRoxa
“AbIntersection” 中的 “unionType” 类型被返回为 never,而后者并非如此。 - Amol Gupta
“never” 是 'A' & 'B' 的正确交集。您认为结果还应该是什么,为什么? - kaya3
1个回答

1

你得到的是 never,因为 TypeScript 无法将类型表示为 'A' & 'B'

看看这个:

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

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

有时会在 TS 挑战问题中发现。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接