【发布时间】:2019-09-10 18:51:50
【问题描述】:
将keyof 与以下类型一起使用会产生属性名称的union:
type Person = {
name: string;
age: number;
location: string;
}
type K1 = keyof Person; // "name" | "age" | "location"
同样,如果我使用利用Exclude 的Omit 助手,我必须为keyof T 提供union 的属性,直观地我会期望提供@987654328 @ of properties 要省略,但事实并非如此:
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
type PersonName = Omit<Person, "location" | "age">;
// type Person = { name: string }
根据我的理解,我认为应该是 type 的组合,因为它需要所有属性的 intersection 而不是属性的 union:
// This isn't valid, but what I'd expect using keyof
type K1 = keyof Person; // "name" & "age" & "location"
type PersonName = Omit<Person, "location" & "age">;
当谈到keyof 时,我对作为union 而不是intersection 的属性键的type 产生的属性的理解在哪里? type 不能像union 所描述的那样,每个属性都是 either 场景。 type 无效,除非它是所有 properties 中的 intersection 正确吗?
【问题讨论】:
标签: typescript