TypeScript内置类型一览(Record<string,any>等等)(上):https://developer.aliyun.com/article/1510475
Omit(省略)
/**
Construct a type with the properties of T except for those in type K.
*/
type Omit = Pick>;
传入一个类型,和这个类型的几个属性,把传入的属性省略掉,组成一个新类型
使用举例
export interface Student { name: string; age: number; class: string; school: string; }
export type PersonAttr = ‘name’ | ‘age’
export type StudentAttr = ‘name’ | ‘age’ | ‘class’ | ‘school’
const student1: Omit = {}
student1报错,提示没有属性’name’、‘age’
NonNullable(不能为null)
/**
Exclude null and undefined from T
*/
type NonNullable = T extends null | undefined ? never : T;
字面意思,不能为空
使用举例
export interface Student { name: string; age: number; }
const student1: NonNullable = null
student1赋值为null会报错(在tsconfig.json配置文件中开启类型检查,“skipLibCheck”: false
)
Parameters(参数)
/**
Obtain the parameters of a function type in a tuple
*/
type Parameters any> = T extends (…args: infer P) => any ? P : never;
获取传入函数的参数组成的类型
使用举例
export interface Student { name: string; age: number; }
export interface StudentFunc {
(name: string, age: number): Student
}
const student1: Parameters
student1的类型为[name: string, age: number]
ConstructorParameters(构造参数)
/**
Obtain the parameters of a constructor function type in a tuple
*/
type ConstructorParameters any> = T extends abstract new (…args: infer P) => any ? P : never;
获取传入构造函数的参数组成的类型
使用举例
export interface Student { name: string; age: number; }
export interface StudentConstructor {
new (name: string, age: number): Student
}
const student1: ConstructorParameters
student1的类型为[name: string, age: number]
ReturnType(返回类型)
/**
Obtain the return type of a function type
*/
type ReturnType any> = T extends (…args: any) => infer R ? R : any;
获取传入函数的返回类型
使用举例
export interface Student { name: string; age: number; }
export interface StudentFunc {
(name: string, age: number): Student
}
const student1: ReturnType = {}
student1的类型为Student
TypeScript内置类型一览(Record<string,any>等等)(下):https://developer.aliyun.com/article/1510478