TypeScript中的Partial、Pick、Record

692 阅读1分钟

Partial

先看官方源码实现:

/** 
 * Make all properties in T optional 
 */                                  
 type Partial<T> = {                 
     [P in keyof T]?: T[P];              
 };

从源码可以看出是把类型T的属性key都设置为了可选属性,组成一个新的类型

type User= {name: string, desc: string}
type Custom = Partial<User>;
等同于
type Custom = {name?: string; decs?: string}

Pick

先看官方源码实现:

/** 
 * From T, pick a set of properties whose keys are in the union K 
 */                                                               
 type Pick<T, K extends keyof T> = {                              
     [P in K]: T[P];                                                  
 };

从源码可以看出是从T类型中挑选一些属性key,组合成一个新的类型

type User= {name: string, desc: string}
type Custom = Pick<User, 'name'>;
等同于
type Custom = {name: string}

Record

先看官方源码实现:

/**
 * Construct a type with a set of properties K of type T 
 */                                                      
 type Record<K extends keyof any, T> = {                 
    [P in K]: T;                                            
 };

从源码可以看出是把一组属性key都设置了为T类型,组成一个新的类型

type User = Record<'name' | 'desc', string>;
等同于
type User = {name: string; desc: string}