Typescript的泛型别名Exclude <T,U>如何工作?

时间:2019-10-20 16:55:13

标签: typescript

通用类型别名定义如下:type Exclude<T,U> = T extends U ? never : T。此定义如何产生一种类型,该类型将排除T中可分配给U的所有属性?根据我的解释,如果T不扩展U,则应产生给定的类型T。例如,在此示例中:type T0 = Exclude<"a" | "b" | "c", "a">应该返回联合类型"a" | "b" | "c",因为它是T定义中的Exclude。有人可以详细解释该定义如何工作吗?

1 个答案:

答案 0 :(得分:3)

条件类型为distributive,即

Exclude<"a"|"b"|"c", "a">

被翻译为

"a" extends "a" ? never : "a" |
"b" extends "a" ? never : "b" |
"c" extends "a" ? never : "c" 

给出never | "b" | "c"或仅给出"b" | "c"