TypeScript中Record是啥?现在让我们来了解一下TypeScript官方的内置类型,让你的开发效率再上一层楼
Partial(部分的)
/** * Make all properties in T optional */ type Partial<T> = { [P in keyof T]?: T[P]; };
作用是让传入类型中的所有属性变成都是可选的
使用举例
export interface Student { name: string; age: number; }
const student1: Student = {}
const student2: Partial = {}
变量student1的类型是Student,Student默认所有的属性都是不能为空的,所有会报错,student2就不会
Required(必须的)
/**
Make all properties in T required
*/
type Required = {
[P in keyof T]-?: T[P];
};
跟Partial的作用是相反的,是让传入类型中的所有属性变成都是必填的
使用举例
export interface Student { name?: string; age?: number; }
const student1: Student = {}
const student2: Required = {}
变量student1的类型是Student,Student默认所有的属性都是可以为空的,所有不会报错,student2会报错
Readonly(只读的)
/**
Make all properties in T readonly
*/
type Readonly = {
readonly [P in keyof T]: T[P];
};
作用是让传入类型中的所有属性变成都是只读的(不能修改属性)
使用举例
export interface Student { name: string; age: number; }
const student1: Student = {
name: ‘张三’,
age: 20
}
student1.age = 21
const student2: Readonly = {
name: ‘李四’,
age: 20
}
student2.age = 21
给student1的属性age重新赋值不会报错,给student2的属性age重新赋值就会报错,因为student2所有的属性都是只读的
Pick(选择)
/**
From T, pick a set of properties whose keys are in the union K
*/
type Pick = {
[P in K]: T[P];
};
作用是选择传入类型中的部分属性组成新类型
使用举例
export interface Student { name: string; age: number; }
const student1: Student = {
name: ‘张三’,
age: 20
}
const student2: Pick = {
name: ‘李四’
}
const student3: Pick = {
name: ‘王五’,
age: 20
}
变量student1可以有所有属性name和age,变量student2就只能有属性name,变量student3加上属性age就会报错
Record(记录)
/**
Construct a type with a set of properties K of type T
/
type Record = {
[P in K]: T;
};
作用是构建一个类型,这个类型用来描述一个对象,这个对象的属性都具有相同的类型
使用举例
export const student1: Record<string, any> = { name: ‘张三’, age: 20 }
Record应该是日常使用频率较高的内置类型了,主要用来描述对象,一般建议是不用Object来描述对象,而是用Record代替,Record几乎可以说是万金油了
Exclude(排除)
/*
Exclude from T those types that are assignable to U
*/
type Exclude = T extends U ? never : T;
针对联合类型(interface这种没用),用人话说,排除相同的,留下不同的
使用举例
export type PersonAttr = ‘name’ | ‘age’
export type StudentAttr = ‘name’ | ‘age’ | ‘class’ | ‘school’
const student1: Exclude
student1就只能被赋值为’class’ 或者’school’
Extract(取出)
/**
Extract from T those types that are assignable to U
*/
type Extract = T extends U ? T : never;
与Exclude相反,针对联合类型,排除不同的的,取出相同的
使用举例
export type PersonAttr = ‘name’ | ‘age’
export type StudentAttr = ‘name’ | ‘age’ | ‘class’ | ‘school’
const student1: Extract
student1就只能被赋值为’name’或者’age’
TypeScript内置类型一览(Record<string,any>等等)(中):https://developer.aliyun.com/article/1510476