TypeScript内置类型一览(Record<string,any>等等)(中):https://developer.aliyun.com/article/1510476
InstanceType(构造返回类型、实例类型)
/**
Obtain the return type of a constructor function type
*/
type InstanceType<T extends abstract new (…args: any) => any> = T extends abstract new (…args: any) => infer R ? R : any;
获取传入构造函数的返回类型
使用举例
const Student = class { name: string; age: number; constructor (name: string, age: number) { this.name = name this.age = age } showInfo () { console.log('name: ', this.name, 'age: ', this.age); } }
const student1: InstanceType<typeof Student> = new Student(‘张三’, 20)
个人认为这是一个非常好用的内置类型,目前在前端项目中,class是用的越来越多了,在TS中,class其实也是可以用作类型声明空间的,用来描述对象类型,但是一般来说好像很少这样用的,一般用interface或者type居多
export class Student { name: string; age: number; }
所以一般就是直接把class用作变量声明空间,但是对于 class new 出的实例,怎么描述它的类型呢,就如上文的,直接const student1: Student
那是铁定会报错的,因为Student用作变量声明空间,没有用作类型声明空间(听起来好绕),这时候就可以用到InstanceType,完美解决问题
Uppercase(大写)
/**
Convert string literal type to uppercase
*/
type Uppercase<S extends string> = intrinsic;
变大写
使用举例
export type StudentSexType = ‘male’ | ‘female’
const studentSex: Uppercase<StudentSexType> = ‘MALE’
Lowercase(小写)
/**
Convert string literal type to lowercase
*/
type Lowercase<S extends string> = intrinsic;
变小写
使用举例
export type StudentSexType = ‘MALE’ | ‘FEMALE’
const studentSex: Lowercase<StudentSexType> = ‘’
Capitalize(首字母大写)
/**
Convert first character of string literal type to uppercase
*/
type Capitalize<S extends string> = intrinsic;
首字母变大写
使用举例
export type StudentSexType = ‘male’ | ‘female’
const studentSex: Capitalize<StudentSexType> = ‘’
Uncapitalize(首字母小写)
/**
Convert first character of string literal type to lowercase
*/
type Uncapitalize<S extends string> = intrinsic;
首字母变小写
使用举例
export type StudentSexType = ‘MALE’ | ‘FEMALE’
const studentSex: Uncapitalize<StudentSexType> = ‘’