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

作者站长头像
站长
· 阅读数 14

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个回答
avatar
test
2024-07-20

看下官方文档: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'.

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容