Record<string, any>
是 TypeScript 中的一种类型定义
Record
是 TypeScript 内置的工具类型,用于表示一个键值对的对象类型<string, any>
是泛型参数:- 第一个参数
string
表示对象的键(key)类型是字符串 - 第二个参数
any
表示对象的值(value)类型可以是任意类型
- 第一个参数
- 整体含义是:一个键为字符串,值可以是任何类型的对象
extraParams?: Record<string, any>; // 新增额外参数属性const params: Record<string, any> = {id: 123, // 数字name: "test", // 字符串enabled: true // 布尔值
};interface User {id: number;name: string;age?: number; // 可选属性
}const handleSelect = (item: User) => {console.log(item.name); // 明确知道 `name` 是 stringconsole.log(item.age); // 可能是 number | undefined
};handleSelect({ id: 1, name: "Alice" }); // OK
handleSelect({ id: 2, name: "Bob", age: 30 }); // OK
handleSelect({ id: 3 }); // 报错:缺少 `name`
总结
Record<string, any>
表示 键是字符串、值任意的对象,比object
更精确,比any
更安全。- 适用场景:当需要表示一个未知结构的对象,但至少确保它是键值对形式时。
- 推荐改进:如果知道对象的具体结构,应该用
interface
或type
替代Record<string, any>
,以获得更好的类型安全。