TS内置类型

124 阅读1分钟

Record

1.内置类型,它的作用是根据传入的索引和值的类型构造心的索引类型

2.当约束索引类型时可以使用Record<string,any>来代替object,Record<string,any>创建了一个key为string类型,值为任意类型的索引类型

语法

type Record<K extends keyof any, T> = {
	[P in K]: T;
};

例子

export const student1: Record<string, any> = {
	name: ‘张三’,
	age: 20
}

Record应该是日常使用频率较高的内置类型了,主要用来描述对象,一般建议是不用Object来描述对象,而是用Record代替,Record<string, any>几乎可以说是万金油了

Record<string, any> matches anything

Record<string, unknown> requires an index signature of any sort in the source type

type A = (() => true) extends Record<string, any> ? true : false; // true
type B = (() => true) extends Record<string, unknown> ? true : false; // false