Typescript Union To Intersection 永远不会返回值 [英] Typescript Union To Intersection returns values as never

查看:34
本文介绍了Typescript Union To Intersection 永远不会返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是参考这篇文章

My question is with reference to this post

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

每当我将联合转换为交集时,我都会失去联合类型,这是我为解决此问题而编写的一些代码

Whenever i convert a union To Intersection i loose the union type, here is some code i wrote to get around the issue

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% 有信心,再考虑一下会很有帮助.当这样的事情会失败以及如何解决同样的问题时,我很好奇.

So i am not 100% confident of the code, it would be really helpful to have a second thought on the same. I'm curios when something like this will fail and how to resolve the same.

提前致谢.

推荐答案

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

You get never because TypeScript can not represent type as 'A' & 'B'.

看看这个:

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

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

发现于 TS 挑战问题 偶尔.

这篇关于Typescript Union To Intersection 永远不会返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆