Record 是 TypeScript 的内置工具类型。
📋 Record 简介
Record<K, T> 是 TypeScript 的工具类型,用于创建一个键为 K 类型,值为 T 类型的对象类型。
📖 语法 ★★★
Record<键的类型, 值的类型>
💡 基本用法
// 定义:键是 string,值是 number
type Scores = Record<string, number>
// 等价于
interface Scores {
[key: string]: number
}
// 使用
const studentScores: Scores = {
math: 90,
english: 85,
science: 95
}
举例
const titles: Record<ModalType, string> = {
add: '新增',
edit: '编辑'
}
解释:
ModalType是'add' | 'edit'Record<ModalType, string>表示:键是'add'或'edit',值是string- 等价于:
{ add: string; edit: string }
📊 TypeScript 编译检查
// ✅ 正确
const titles: Record<ModalType, string> = {
add: '新增',
edit: '编辑'
}
// ✅ 正确(顺序无关)
const titles: Record<ModalType, string> = {
edit: '编辑',
add: '新增'
}
// ❌ 错误:缺少 'add' 属性
const titles: Record<ModalType, string> = {
edit: '编辑' // 缺少 'add'
}
// ❌ 错误:多了 'view' 属性
const titles: Record<ModalType, string> = {
add: '新增',
edit: '编辑',
view: '查看' // 不允许,因为 ModalType 没有 'view'
}
// ❌ 错误:值不是 string
const titles: Record<ModalType, string> = {
add: 123, // 应该是 string
edit: '编辑'
}
