以下代码截取自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;