Typescript中的Record

684 阅读2分钟

Record<Types, Keys>

2.1版本以上, 开箱即用
定义对象的key和value, 复杂类型中约束定义属性和值

www.typescriptlang.org/docs/handbo… 官方文档中写道

Constructs an object type whose property keys are `Keys` and whose property values  are `Type`.                 
This utility can be used to map the properties of a type to another type.
//构造一个对象类型,`Keys` 表示对象的属性键 、`Type` 表示对象的属性值,用于将一种类型属性映射到另一种类型

1.Record也可以索引签名

type StudentAge = {[name: string]: number}
//访问带有方括号的对象的方式叫索引签名,用于未知的键值对象
type StudentAge = Record<string, number>
//用Record实现索引签名

2.Record结合联合属性限制属性,约束定义一个类型

//联合属性限制属性值,约束定义一个类型, Record类型使用使得更简明
type Names = "age" | "name" | "sex"
type Types = number | string 
interface StudentsInfoType extends Record < Names, Types> {
    age: number
    name: string
    sex: string
}
const students: StudentsInfoType = {
    age: 11,
    name: 'hh',
    sex: "man"
}


type Types = 'price' | 'name'
interface Keys {id: number, seq: number}
const students: Record<Types, Keys> = {
    price: { id: 1, seq:0 },
    name: {id: 2, seq:1}
}
//在复杂类型中非常有用

3.Record与keyof结合,转换成其他类型

interface Human {
    name: string,
    age: number,
}

type HumanChangeType = Record<keyof Human, string>
const hh: HumanChangeType = {
    name: "hh",
    age: '1'
}
//便捷转换值类型

4. RecordPartial 和 Intersection 类型一起工作,高级用法

type Aname = "sA"
type Bname = "sB"
const benefits: Partial<Record<Aname, 'aa'> & Record<Bname, 'bb'>> = {}
benefits.sA = "aa" 
benefits.sB = "aa" //报错只能是 "bb"
//通过 `Record`、`Partial` 和 `Intersection` 类型一起工作,此代码创建了一个强类型的`benefits`对象,
//并在键和值类型之间建立关联.强类型对象使得在编译时更容易捕获错误,使 IDE 在键入时更容易标记错误,
//并提供具有自动完成功能的智能提示 ???

Record是一个有用和简要的工具类型,可以让你的代码更健壮

链接: blog.csdn.net/weixin_4049…