【问题标题】:Typescript Union To Intersection returns values as neverTypescript Union To Intersection 返回值从不
【发布时间】: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% 有信心,重新考虑一下会很有帮助。 当这样的事情会失败以及如何解决同样的事情时,我很好奇。

提前致谢。

【问题讨论】:

  • 我不明白这一点。给定AB 类型,UnionToIntersection&lt;A | B&gt; 按预期返回A &amp; B。没有never,没有过度工程。可能是我没有得到你想要得到的东西,抱歉。
  • 'AbIntersection' 中的 'unionType' 类型返回为从不返回,后者不是这种情况......
  • never'A' &amp; 'B' 的正确交集。你认为结果应该是什么,为什么?

标签: typescript typescript-typings


【解决方案1】:

您得到never,因为TypeScript 不能将类型表示为'A' &amp; 'B'

看看这个:

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

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

偶尔会在TS Challenge issue 中找到。

【讨论】:

    猜你喜欢
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2020-04-23
    相关资源
    最近更新 更多