keyof
Object.keys 用于提取对象类型的键,keyof 则用于提取 interface 的键。
interface Point {
x: number;
y: number;
}
// type keys = "x" | "y"
type keys = keyof Point;
in
in 用来遍历枚举类型。
type keys = "x" | "y"
type Obj = {
[p in keys]: string;
} // -> { x: string, y: string }
keyof 产生枚举类型,in 使用枚举类型遍历,所以他们经常一起使用,看下 Partial 源码:
type Partial<T> = { [P in keyof T]?: T[P] };
Partial 源码中,keyof 拿到 T 的所有属性值,然后通过 in 遍历这些属性值,赋值给 P,最后通过 T[P] 取得相应的属性值。
Required
将类型中所有选项都变成必选,去除所有的非必须。
/**
* Make all properties in T required
*/
type Required<T> = {
[P in keyof T]-?: T[P];
};
例如:
export interface Contact{
name: string;
phone?: string;
email?: string;
avatar?: string;
userid?: string;
}
export interface RequiredContact= Required<Contact>
RequiredContact {
name: string;
phone: string;
email: string;
avatar: string;
userid: string;
}
Partial
将类型中所有选项都变成可选。
/**
* Make all properties in T optional
*/
type Partial<T> = {
[P in keyof T]?: T[P];
};
例如:
export interface Contact{
name?: string;
phone: string;
email?: string;
avatar: string;
userid?: string;
}
export interface RequiredContact= Partial<Contact>
RequiredContact {
name?: string;
phone?: string;
email?: string;
avatar?: string;
userid?: string;
}
Pick
选取类型中指定类型。
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
例如:
export interface Contact{
name?: string;
phone: string;
email?: string;
avatar: string;
userid?: string;
}
export interface ContactPick extends Pick<Contact, 'name' | 'phone'> {};
ContactPick {
name?: string;
phone: string;
}
Omit
去除类型中的某些类型
/**
* Construct a type with the properties of T except for those in type K.
*/
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
例如:
export interface Contact{
name?: string;
phone: string;
email?: string;
avatar: string;
userid?: string;
}
export type OmitEmailContact = Omit<Contact, 'email' >;
OmitEmailContact {
name?: string;
phone: string;
avatar: string;
userid?: string;
}
参考
- https://www.react-native.cn/docs/debugging
- https://blog.csdn.net/jojo1001/article/details/121074549
- https://moin.world/2017/06/18/10-typescript-features-you-might-not-know/
- https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html
- https://www.typescriptlang.org/docs/handbook/advanced-types.html
- https://juejin.cn/post/6844903863791648782#comment
- https://blog.csdn.net/qq_43869822/article/details/121664818?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-121664818-blog-121074549.pc_relevant_paycolumn_v3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-121664818-blog-121074549.pc_relevant_paycolumn_v3&utm_relevant_index=2