TypeScript 中的 Record:在实践中理解
\n\n想象一下,您正在编写一个学习英语单词的应用程序。您需要存储翻译:cat → 猫,dog → 狗。如何在 TypeScript 中正确地对其进行类型化?您可以创建一个接口,但如果键事先未知怎么办?或者键太多?这时 Record 就派上用场了——它是最有用但经常被低估的实用类型之一。
在本文中,我们将通过实际示例来解析 TypeScript 中的 Record 类型,这些示例您可以立即应用到自己的项目中。没有枯燥的理论——只有实践。
\n\nTypeScript 中的 Record 是什么?简单来说
\n\nRecord<K, V> 是一个内置的实用类型,它创建一个对象,其中所有键的类型为 K,所有值的类型为 V。
您可以将其视为一个具有固定键集的 类型化字典 或 映射。
基本写法如下:
\n\n// 普通对象\nconst userRoles: Record<string, string> = {\n admin: '管理员',\n user: '用户',\n guest: '访客'\n};\n\n这里 Record<string, string> 的意思是:“一个对象,其中键是字符串,值也是字符串”。简单明了。
Record 比普通接口好在哪里?
\n\n- \n
- 键的灵活性:您可以通过联合类型指定一组特定的键。 \n
- 简洁性:无需手动描述每个字段。 \n
- 安全性:TypeScript 会检查您是否只使用了允许的键。 \n
Record 与普通对象:直观示例
\n\n假设我们有订单状态:pending、shipped、delivered。如果不使用 Record,您必须编写一个包含三个字段的接口:
interface OrderStatusMap {\n pending: string;\n shipped: string;\n delivered: string;\n}\n\nconst statusDescriptions: OrderStatusMap = {\n pending: '等待处理',\n shipped: '已发货',\n delivered: '已送达'\n};\n\n而使用 Record,则更紧凑、更直观:
\n\ntype OrderStatus = 'pending' | 'shipped' | 'delivered';\n\nconst statusDescriptions: Record<OrderStatus, string> = {\n pending: '等待处理',\n shipped: '已发货',\n delivered: '已送达'\n};\n\n优点:如果您尝试在对象中添加 cancelled,TypeScript 会立即指出错误——联合类型中没有这个状态。
Record 的 5 个最佳实际用例
\n\n让我们看看 Record 在哪些地方真正简化了生活。
\n\n1. 应用程序配置
\n使用已知键但不同类型值存储设置:
\n\ntype ConfigKeys = 'apiUrl' | 'timeout' | 'retryCount';\ntype ConfigValue = string | number | boolean;\n\nconst appConfig: Record<ConfigKeys, ConfigValue> = {\n apiUrl: 'https://api.example.com',\n timeout: 5000,\n retryCount: 3\n};\n\n2. 枚举或常量映射
\n经常需要将代码与其人类可读的名称对应起来:
\n\nenum HttpStatus {\n OK = 200,\n NotFound = 404,\n Error = 500\n}\n\nconst statusMessages: Record<HttpStatus, string> = {\n [HttpStatus.OK]: '一切正常',\n [HttpStatus.NotFound]: '未找到',\n [HttpStatus.Error]: '服务器错误'\n};\n\n3. 表单与验证
\nRecord 非常适合按字段存储验证错误:
\n\ntype FormFields = 'email' | 'password' | 'name';\ntype ValidationErrors = Record<FormFields, string | null>;\n\nconst errors: ValidationErrors = {\n email: '邮箱格式不正确',\n password: null,\n name: '姓名是必填项'\n};\n\n4. 数据缓存
\n使用标识符作为键模拟缓存:
\n\ntype UserI