[TypeScript] 常用类型

2025-09-03

Record

interface ButtonConfig {
  type?: 'primary' | 'success' | 'warning' | 'danger' | 'info' | 'default';
  label: string;
}

const buttonConfigs: Record<string, ButtonConfig> = {
  view: { label: '查看' },
  edit: { type: 'warning', label: '编辑' },
  delete: { type: 'danger', label: '删除' }
};

解释(简明)

  • Record<string, ButtonConfig> 是 TypeScript 内置的泛型工具类型,表示“以字符串为键、以 ButtonConfig 为值”的对象类型。

  • 换句话说,它声明该变量是一个键为任意字符串、值必须符合 ButtonConfig 结构的映射(字典/对象)。

等价写法

  • 等价于带索引签名的写法:

    • interface MyMap { [key: string]: ButtonConfig }

    • 或直接类型别名:type MyMap = { [key: string]: ButtonConfig }

在您代码里的含义

  • const buttonConfigs: Record<string, ButtonConfig> = { ... } 意味着 buttonConfigs 是一个以字符串键(比如 'view', 'edit', 'delete')索引并返回 ButtonConfig 的对象。TypeScript 会检查对象中每个值都符合 ButtonConfig 类型。

注意与建议

  • Record<string, ButtonConfig> 允许任意字符串键,因此在使用不存在的键索引(如 buttonConfigs[someUnknown])时,类型上仍被认为是 ButtonConfig,但运行时可能为 undefined。因此代码中用 || { label: '' } 做了防护是合理的。

  • 如果键是已知的一组(例如只允许 'view'|'edit'|'delete'),更严格的类型会更安全:

    • type BtnKeys = 'view' | 'edit' | 'delete'

    • const buttonConfigs: Partial<Record<BtnKeys, ButtonConfig>> = { ... } 这样能让 TypeScript 在访问或遗漏某些已知键时给出更明确的提示。

简短示例

  • 当前(允许任意键):

    • const buttonConfigs: Record<string, ButtonConfig> = { view: { label: '查看' } }

  • 严格版本(限定键):

    • type BtnKeys = 'view'|'edit'|'delete'

    • const buttonConfigs: Partial<Record<BtnKeys, ButtonConfig>> = { view: { label: '查看' } }

PREV
[Vue] 检测本组件的插槽是否被使用
NEXT
文件夹内容校验