我的问题是关于这篇文章
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/