【TypeScript】直接使用工具类型 Exclude 的原理进行推导,为什么推出来的结果不太对呢?

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"
阅读 1.4k
1 个回答
✓ 已被采纳

看下官方文档:https://www.typescriptlang.or... ,这里解释的比较清楚。
中文资料可看:https://www.tslang.cn/docs/re...

简单来说就是:

MyExclude<case1, case2>; 等价于:

('a' extends case2 ? never : 'a') | ('b' extends case2 ? never : 'b') | ('c' extends case2 ? never : 'c')

// =>  never | 'b' | 'c' => 'b' | 'c'

type result02 = case1 extends case2 ? never : case1 就是字面意思:

'a' | 'b' | 'c' extends 'b' | 'c',成立,则推断出为 'a' | 'b' | 'c'.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进