Skip to content
本页内容

在 TypeScript 中,Record 是一个内置的工具类型(Utility Type),用于构造一个对象类型,其键类型和对应的值类型都可以指定,常用于在类型层面对对象结构进行精确控制。


✅ 基本语法

ts
Record<Keys, Type>
  • Keys:表示键的集合(可以是 stringnumbersymbol、联合类型等)
  • Type:所有键对应的值的类型

📌 示例讲解

1. 基本用法

ts
type UserRole = 'admin' | 'user' | 'guest';

const roles: Record<UserRole, number> = {
  admin: 1,
  user: 2,
  guest: 3,
};

上例中:roles 是一个对象,必须包含 'admin' | 'user' | 'guest' 这三个键,每个键的值类型必须是 number


2. 和接口/类型结合使用

ts
type UserInfo = {
  name: string;
  age: number;
};

type UserMap = Record<string, UserInfo>;

const users: UserMap = {
  jack: { name: 'Jack', age: 28 },
  jill: { name: 'Jill', age: 25 },
};

Record<string, UserInfo> 表示一个对象,其所有键为字符串,值为 UserInfo 类型。


3. 配合联合类型自动生成对象结构

ts
type Status = 'success' | 'error' | 'loading';

type StatusColor = Record<Status, string>;

const statusColor: StatusColor = {
  success: 'green',
  error: 'red',
  loading: 'gray',
};

非常适合替代手写冗长的对象类型定义。


4. 用于从已有类型中派生新结构

ts
interface Config {
  port: number;
  host: string;
  protocol: 'http' | 'https';
}

type OptionalConfig = Record<keyof Config, string>;

const optional: OptionalConfig = {
  port: '3000',
  host: 'localhost',
  protocol: 'http',
};

keyof Config 会提取出 'port' | 'host' | 'protocol',构造成键,值类型为 string


🔍 使用 Record 的实际场景

✅ 场景 1:创建映射表(map)

ts
const langMap: Record<'en' | 'zh' | 'jp', string> = {
  en: 'Hello',
  zh: '你好',
  jp: 'こんにちは',
};

✅ 场景 2:限制对象键的类型

ts
type ButtonType = 'primary' | 'secondary' | 'danger';

type ButtonLabels = Record<ButtonType, string>;

const labels: ButtonLabels = {
  primary: 'Submit',
  secondary: 'Cancel',
  danger: 'Delete',
};

✅ 场景 3:替代冗长的接口定义

ts
// 比这样更简洁:
interface Permissions {
  read: boolean;
  write: boolean;
  delete: boolean;
}

// 可以用 Record 重写:
type PermissionKey = 'read' | 'write' | 'delete';
type Permissions = Record<PermissionKey, boolean>;

⚠️ 注意事项

说明
所有键都是必填的`Record<'a'
键的类型不能是任意对象类型Record 的键只能是 stringnumbersymbol,不能是 {}
和其他工具类型可以组合使用比如 Partial<Record<...>>Readonly<Record<...>>

🧠 类似工具类型对比

工具类型作用
Record<K, T>构造一个以 K 为键、T 为值的对象类型
Partial<T>将 T 中的所有属性设为可选
Pick<T, K>从 T 中挑选出一部分属性组成新类型
Omit<T, K>从 T 中排除某些属性组成新类型

🧪 小测试:判断是否正确使用 Record

ts
type Keys = 'foo' | 'bar';
type MyRecord = Record<Keys, number>;

const data: MyRecord = {
  foo: 123,
  bar: 456,
  // baz: 789, ❌ 会报错,超出 Keys 范围
};