Record
Record 的定义
type Record<K extends keyof any, V> = {
[P in K]: V;
}
Record 的使用
type Score = Record<string, number>;
const score: Score = { math: 90, english: 90 };
console.log(score);
type Role = 'admin' | 'user' | 'guest';
type Permission = Record<Role, boolean>;
const perms: Permission = { admin: true, user: false, guest: false };
console.log(perms);
// 1. keyof
type User = { name: string; age: number };
type UserFlags = Record<keyof User, boolean>;
const u: UserFlags = {
name: true,
age: true
};
console.log(u);
// 2. 嵌套 record
type NestedConfig = Record<string, Record<string, number>>;
const config: NestedConfig = {
server: {
port: 8080,
timeout: 3000
}
};
// 3. 联合类型
type Status = Record<string, 'active' | 'inactive' | 'pending'>;
const s: Status = {
a: 'active',
b: 'inactive',
c: 'pending'
};
// 4. 结合泛型构建动态映射
function toMap<T>(arr: T[], key: keyof T): Record<string, T> {
return arr.reduce(
(acc: Record<string, T>, item: T) => {
acc[String(item[key])] = item;
return acc;
},
{} as Record<string, T>
);
}