Utility Types 中的 Exclude 的理解
来源:5-10 TS的Utility Types-Pick、Exclude、Partial和Omit实现

qq_小江南_04298178
2021-05-29
Exclude 的实现如下:
type Exclude<T, U> = T extends U ? never : T;
T extends U 的意思是说 T 要是 U 的子集
代码
type Person ={
name:string,
age:number
}
type PersonKeys= keyof Person
type Age = Exclude<PersonKeys,'name'>
const age1:Age='age'
按照上面说的 T 是 U 的子集对应到 type Age 中就是判断 PersonKeys 是不是 ‘name’ 的子集,是的话移除 PersonKeys 否则保留 PersonKeys???
但实际使用效果感觉是判断 后面参数是不是前面参数的子集,是的话就不保留,不是就保留,实际与预期不符?是我哪里理解出来问题?
写回答
1回答
-
Nolan
2021-06-01
对比方法不是你说的那样,给你举个例子:
typeT0=Exclude<"a" | "b" | "c", "a">;
(type T0 = "b" | "c")
这里是这样对比的:
'a' extends 'a' ? never : 'a'
'b' extends 'a' ? never : 'b'
'c' extends 'a' ? never : 'c'
你看到了,它们是一个一个上去对比的,不是一起上去对比的
00
相似问题