Record
Record<K,T>构造具有给定类型T的一组属性K的类型。在将一个类型的属性映射到另一个类型的属性时,Record非常方便。
他会将一个类型的所有属性值都映射到另一个类型上并创造一个新的类型。
interface EmployeeType {
id: number
fullname: string
role: string
}
let employees: Record<number, EmployeeType> = {
0: { id: 1, fullname: "John Doe", role: "Designer" },
1: { id: 2, fullname: "Ibrahima Fall", role: "Developer" },
2: { id: 3, fullname: "Sara Duckson", role: "Developer" },
}
在这里,它期望数字作为类型,属性值的类型是EmployeeType,因此具有id,fullname和role字段的对象。
常用格式
type proxyKType = Record<K,T>
会将K中的所有属性值都转换为T类型,并将返回的新类型返回给proxyType,K可以是联合类型、对象、枚举…
type petsGroup = 'dog' | 'cat' | 'fish';
interface IPetInfo {
name:string,
age:number,
}
type IPets = Record<petsGroup, IPetInfo>;
const animalsInfo:IPets = {
dog:{
name:'dogName',
age:2
},
cat:{
name:'catName',
age:3
},
fish:{
name:'fishName',
age:5
}
}
也可以自己在第一个参数后追加额外的值,如下面:
type petsGroup = 'dog' | 'cat' | 'fish';
interface IPetInfo {
name:string,
age:number,
}
type IPets = Record<petsGroup | 'otherAnamial', IPetInfo>;
const animalsInfo:IPets = {
dog:{
name:'dogName',
age:2
},
cat:{
name:'catName',
age:3
},
fish:{
name:'fishName',
age:5
},
otherAnamial:{
name:'otherAnamialName',
age:10
}
}