Typescript Union To Intersection 返回值为 never

标签 typescript typescript-typings

我的问题是关于这篇文章

Transform union type to intersection type

每当我将 union 转换为 Intersection 时,我都会松开 union 类型,这是我为解决该问题而编写的一些代码

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% 有信心,重新考虑一下代码真的很有帮助。 我很好奇这样的事情何时会失败以及如何解决。

提前致谢。

最佳答案

你得到 never 因为 TypeScript 不能将类型表示为 'A' & 'B'

检查一下:

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

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

它是在 TS Challenge issue 中发现的偶尔。

关于Typescript Union To Intersection 返回值为 never,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61693847/

相关文章:

node.js - Firebase Functions 模拟器错误 : Cannot find module '../service-account.json'

typescript - 在类中使用 requestAnimationFrame

javascript - 如何从 Promise 中返回值?

typescript - 可以弄清楚如何让 TypeScript 对返回的 Promise 感到满意

typescript - 元素隐式具有 'any' 类型,因为类型 '{}' 没有索引签名。 [7017]

javascript - react-native-svg 中 <Rect/> 的动画宽度

javascript - Angular - innerHTML,转义小于/大于字符,但保持 <br/> 不变

Angular Cli - 未找到 Dojo 模块

reactjs - React 15 + Typescript : React. FormEvent<T> 类型不完整?