typescript - 并集到交集

标签 typescript

浏览TypeScript challenges时,我遇到了一个特别有趣的:How to turn a union to an intersection .

我自己无法弄清楚,我转向解决方案,在那里我找到了一个很好的方法 here并给出了更好的解释 here作者:@jcalz。

我遇到的唯一问题是 question :实际上,用户尝试将解决方案分解为多个单独的语句,令我惊讶的是,结果并不相同。我们得到的是 foo | 而不是 foo & bar。将解决方案作为“一行”重新组合在一起,结果就会“恢复”:foo & bar

// Type definition
type UnionToIntersection<U> = (U extends any ? (arg: U) => any : never) extends ((arg: infer I) => void) 
  ? I 
  : never;

// As expected 👍 ('foo' & 'bar' is never)
type I = UnionToIntersection<'foo' | 'bar'>;  // never

// Let's break-down `UnionToIntersection`

type A = 'foo' | 'bar';

type B = A extends any ? (arg: A) => any : never // (arg: A) => any;

// This should have been 'foo' & 'bar' (never) just like `type I` 🤯
type C = B extends ((arg: infer I) => void) ? I : never //  'foo' | 'bar'

这是怎么回事? I 型C 型 不应该是一样的吗?

最佳答案

effectively a user tried to break down the solution in multiple separate statements

用户犯了一个错误。在原始类型中,U 是一个泛型类型,它获取 distributed在条件中。

B中,您使用的A不是泛型类型。不进行任何分发。

如果我们修改 B 使其也具有泛型类型 U(我们默认为 A),我们将看到相同的结果结果从不

type B<U = A> = U extends any ? (arg: U) => any : never 
type C = B extends ((arg: infer I) => void) ? I : never 
//   ^? never

Playground

关于typescript - 并集到交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74003303/

相关文章:

arrays - 如何从 Angular2(Typescript) 中的 Json 数组中获取值的总和

angular - Angular 模板中的可选链接

angular - 无法绑定(bind)到 'countUp',因为它不是 'h1' 的已知属性。 countup.js-angular2

javascript - Typescript 和自定义元素属性编译问题

javascript - 从类创建派生类型,但省略构造函数( typescript )

typescript - IntelliJ IDEA : How do I disable/ignore specific auto import suggestions?

node.js - Firebase Cloud Functions 与 TypeScript : Realtime Database update ends with success but not updates anything, JS 工作正常

javascript - 在JS中对json数组使用find方法时仅发送键值

angular - 如何解决这个依赖问题

javascript - 更改 Angular 8 和 Angular Material 中的日期时间格式