以下代码截取自 es5 的声明
前提说明:T 是接口,方便理解,实际情况可能是复杂类型
interface T {
name: string
age: number
sex: ‘male’ | ‘female’
}
还有一点:keyof T === ‘name’ | ‘age’ | ‘sex’
/**
* T 的属性变成可选的
*/
type Partial<T> = {[P in keyof T]?: T[P];
};
/**
* T 的属性变成必选的
*/
type Required<T> = {[P in keyof T]-?: T[P];
};
/**
* T 的属性变成只读的
*/
type Readonly<T> = {readonly [P in keyof T]: T[P];
};
/**
* 得到 T,K 共有的属性
*/
type Pick<T, K extends keyof T> = {[P in K]: T[P];
};
/**
* 把 K 的 key 值类型设置为 T
*/
type Record<K extends keyof any, T> = {[P in K]: T;
};
/**
* U 的属性在 T 中都能找到时返回 never,否则返回 T
*/
type Exclude<T, U> = T extends U ? never : T;
/**
* U 的属性在 T 中都能找到时返回 T,否则返回 never
*/
type Extract<T, U> = T extends U ? T : never;
/**
* 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>>;
/**
* Exclude null and undefined from T
*/
type NonNullable<T> = T extends null | undefined ? never : T;
/**
* Obtain the parameters of a function type in a tuple
*/
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;
/**
* Obtain the parameters of a constructor function type in a tuple
*/
type ConstructorParameters<T extends new (...args: any) => any> = T extends new (...args: infer P) => any ? P : never;
/**
* Obtain the return type of a function type
*/
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
/**
* Obtain the return type of a constructor function type
*/
type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;