typescript常见类型声明

以下代码截取自es5的声明
前提说明:T是接口,方便理解,实际情况可能是复杂类型
interface T {
name: string
age: number
sex: 'male' | 'female'
}
还有一点:keyof T === 'name' | 'age' | 'sex'

/**
 * T的属性变成可选的
 */
type Partial = {
    [P in keyof T]?: T[P];
};

/**
 * T的属性变成必选的
 */
type Required = {
    [P in keyof T]-?: T[P];
};

/**
 * T的属性变成只读的
 */
type Readonly = {
    readonly [P in keyof T]: T[P];
};

/**
 * 得到T,K共有的属性
 */
type Pick = {
    [P in K]: T[P];
};

/**
 * 把K的key值类型设置为T
 */
type Record = {
    [P in K]: T;
};

/**
 * U的属性在T中都能找到时返回never,否则返回T
 */
type Exclude = T extends U ? never : T;

/**
 * U的属性在T中都能找到时返回T,否则返回never
 */
type Extract = T extends U ? T : never;

/**
 * Construct a type with the properties of T except for those in type K.
 */
type Omit = Pick>;

/**
 * Exclude null and undefined from T
 */
type NonNullable = T extends null | undefined ? never : T;

/**
 * Obtain the parameters of a function type in a tuple
 */
type Parameters any> = T extends (...args: infer P) => any ? P : never;

/**
 * Obtain the parameters of a constructor function type in a tuple
 */
type ConstructorParameters any> = T extends new (...args: infer P) => any ? P : never;

/**
 * Obtain the return type of a function type
 */
type ReturnType any> = T extends (...args: any) => infer R ? R : any;

/**
 * Obtain the return type of a constructor function type
 */
type InstanceType any> = T extends new (...args: any) => infer R ? R : any;

你可能感兴趣的:(typescript,extends,类型判断)