You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+TypeScript中DisplayNames类型循环索引报错的解决方法

问题解决与优化方案

错误原因

TypeScript 报错是因为 Object.entries(props) 返回的键类型是 string,而 DisplayNames 的键是 keyof Props 字面量类型(比如 "name"、"businessKey")。TypeScript 无法确认任意 string 都能合法索引 DisplayNames,所以抛出类型不安全的警告。

快速修复方案

方案1:类型断言

将遍历得到的键断言为 keyof Props,明确告诉编译器这个键是合法的:

Object.entries(props).map(([key, value]) => {
  return (
    <>
      <p>{displayNames[key as keyof Props]}</p>
      <p>{value}</p>
    </>
  )
})

方案2:提取合法键数组

先把 props 的键转换为 keyof Props 类型的数组,再遍历,避免类型断言:

const propsKeys = Object.keys(props) as Array<keyof Props>;

propsKeys.map(key => (
  <>
    <p>{displayNames[key]}</p>
    <p>{props[key]}</p>
  </>
))

更优实现方式

推荐使用配置数组统一管理字段的键和显示名,这种方式不仅类型安全,还能灵活控制显示顺序、添加额外配置(比如是否隐藏、自定义渲染逻辑):

// 定义字段配置数组,集中管理键与显示名
const fieldConfigs: Array<{ key: keyof Props; label: string }> = [
  { key: "name", label: "Name" },
  { key: "businessKey", label: "Business Key" },
  { key: "isin", label: "Is In" },
  { key: "assetCurrency", label: "Asset Currency" },
  { key: "assetType", label: "Asset Type" },
  { key: "assetSector", label: "Asset Sector" },
  { key: "riskCurrency", label: "Risk Currency" },
  { key: "domicile", label: "Domicile" },
  { key: "industry", label: "Industry" },
  { key: "priceUnit", label: "Price Unit" },
];

// 组件内遍历配置数组
fieldConfigs.map(({ key, label }) => (
  <>
    <p>{label}</p>
    <p>{props[key]}</p>
  </>
))

这种方案的优势:

  • 完全不需要类型断言,TypeScript 能自动推导类型,类型安全
  • 可以通过调整数组顺序直接控制页面上字段的显示顺序
  • 后续如果需要给某些字段添加特殊逻辑(比如只在特定条件下显示),只需在配置数组中添加对应属性即可扩展

内容的提问来源于stack exchange,提问作者Boris Grunwald

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:55:36