无法正确理解打字稿中的

无法正确理解打字稿中的

本文介绍了无法正确理解打字稿中的`Exclude<T, U>`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打字稿中有类型定义:

type Exclude<T, U> = T extends U ? never : T;

我们可以用它从另一个类型中排除一个类型:

We can use it to exclude a type from another type:

type AB = 'a' | 'b'
type AC = 'a' | 'c'

type X = Exclude<AB, AC>

类型 X 现在是 b.

但是当我直接使用Exclude的内容时:

But when I use the content of Exclude directly:

type X = AB extends AC ? never : AC;

类型X不同,不再是b,而是AC.

The type X is different, it's not b anymore, it's AC.

我不明白为什么它的行为不同.

I can't understand why it behaves differently.

推荐答案

首先,如果替换内容,X 将是 type X = AB extends AC ?从不:AB;.但这也不会给你相同的结果.

Firstly if you replace the content, X would be type X = AB extends AC ? never : AB;. But that will not give you the same result either.

原因是条件类型在涉及裸类型参数时有一种特殊的行为,如果它们是联合,它们会分布在它们之上.因此,当您使用 Exclude 时,联合的每个成员都单独通过条件并合并结果.所以 Exclude 等价于:

The reason is that conditional types have a special behavior when it comes to naked type parameters, they distribute over them if they are a union. So when you use Exclude, each member of the union is separately put through the condition and the result is unioned. So Exclude<AC, AB> is equivalent to:

type X = ('a' extends AC ? never : 'a') | ('b' extends AC ? never : 'b')

除了裸类型参数(裸意味着 T 不用于另一种类型,例如元组、数组或作为另一个泛型类型的参数)外,不会发生这种分配行为,这就是直接在条件中使用类型不会产生相同结果的原因.您可以在此处

This distributive behavior does not occur with anything except naked type parameters (naked meaning T is not used in another type, such as a tuple, an array or as a parameter to another generic type), this is why using the type directly in the condition does not yield the same result. You can read more here

这篇关于无法正确理解打字稿中的`Exclude<T, U>`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:08