为什么此 CustomExtract 返回与默认 Extract 不同的结果? [英] Why this CustomExtract returns an different result from default Extract?

查看:48
本文介绍了为什么此 CustomExtract 返回与默认 Extract 不同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码解释了我的问题:

type A = {
  a: number,
} | null

// Extract as defined in lib.es5.d.ts
type Extract<T, U> = T extends U ? T : never;

type CustomExtract = A extends null ? A : never;

type Result1 = Extract<A, null> // null
type Result2 = CustomExtract;   // never

Extract 和 CustomExtract 是相同的代码,区别在于 Extract 是泛型类型.

Extract and CustomExtract are the same code, with the difference that Extract is a generic type.

此外,作为相关示例,string |null 不扩展 null.

Also, as related example, string | null does not extends null.

那么,在这个主题中,类型是如何真正起作用的?我可以想象它可能会为每种类型的联合运行泛型类型,然后联合所有结果,但我想要真正的技术定义和它的工作.

So, how types really works under the hoods at this topic? I can imagine it maybe runs the generic type for each type of the union and then unionize all the results, but I want the real technical definition and working of it.

推荐答案

区别在于 Extract 是一个 distributive 条件类型,而您的 CustomExtract 不是.

The difference is that Extract is a distributive conditional type, while your CustomExtract is not.

为了 X extends Y 形式的条件类型?A : B 是分布式的,被检查的类型X必须是一个裸类型参数";也就是说,一个类型参数,比如interface Foo中的T.{...}naked 因为它只是被检查的类型参数(即,T extends ...)而不仅仅是一些表达式包括类型参数(例如,Promise extends ...[T] extends ...).

In order for a conditional type of the form X extends Y ? A : B to be distributive, the checked type X must be a "naked type parameter"; that is, a type parameter like T in interface Foo<T> {...}, and naked in that it is just the type parameter being checked (i.e., T extends ...) and not just some expression that includes the type parameter (e.g., Promise<T> extends ... or [T] extends ...).

正如您所猜测的,分配条件类型确实评估为检查类型 T 的每个联合元素的条件的联合.所以如果 F 是一个分配条件类型,那么 F 将被评估为 F|F B|F.一个潜在的问题是 F 将被评估为 never,无论 F 的细节是什么(只要它是可分配的),因为 never 被认为是 "空联合类型".

As you surmised, distributive conditional types do indeed evaluate as the union of the conditional for each union element of the checked type T. So if F<T> is a distributive conditional type, then F<A | B | C> will be evaluated as F<A> | F<B> | F<C>. One potential catch is that F<never> will be evaluated as never no matter what the details of F are (as long as it's distributive), as never is considered to be the "empty union type".

有关更多信息,请参阅我的其他答案,了解什么是分布式条件类型及其工作原理.

For further information, see my other answer about what distributive conditional types are and how they work.

这篇关于为什么此 CustomExtract 返回与默认 Extract 不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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