MyExclude:从联合类型 T 中排除 U 的类型成员,来构造一个新的类型。
result01 使用 MyExclude ,结果能够正确的排掉 U,
但是我直接对 result00 中使用 Exclude 的原理,为什么推出来的结果不一样呢?
type case1 = "a" | "b" | "c";
type case2 = "a";
type MyExclude<T, U> = T extends U ? never : T;
type result01 = MyExclude<case1, case2>;
// type result01 = "b" | "c"
type result02 = case1 extends case2 ? never : case1;
// type result02 = "a" | "b" | "c"
看下官方文档:https://www.typescriptlang.or... ,这里解释的比较清楚。
中文资料可看:https://www.tslang.cn/docs/re...
简单来说就是:
MyExclude<case1, case2>;
等价于:而
type result02 = case1 extends case2 ? never : case1
就是字面意思:'a' | 'b' | 'c' extends 'b' | 'c'
,成立,则推断出为'a' | 'b' | 'c'
.