TypeScript如何根据属性名从对象中取值 解决索引类型报错问题
错误原因
TypeScript 会自动推导 chipColors 的键为字面量联合类型 'delivered' | 'pending' | 'canceled',而 row.order_status 被推导为宽泛的 string 类型,无法保证一定是 chipColors 包含的键,因此触发类型报错。JavaScript 是动态类型语言,不会做静态类型检查,所以不会提前抛出该错误。
解决方法
方案1:显式声明对象索引签名(最简单)
直接告诉 TypeScript 该对象接受任意字符串作为键,适合不需要强类型校验的简单场景:
// 声明对象的键为string类型,值为string类型 const chipColors: Record<string, string> = { delivered: "success", pending: "warning", canceled: "danger" }
方案2:限定状态类型(最推荐,类型安全)
提前定义订单状态的联合类型,从源头约束 order_status 的取值范围,避免非法值:
// 定义合法的订单状态枚举 type OrderStatus = 'delivered' | 'pending' | 'canceled' // 约束chipColors的键必须是合法订单状态 const chipColors: Record<OrderStatus, string> = { delivered: "success", pending: "warning", canceled: "danger" } // 给row的类型指定order_status的类型为OrderStatus interface OrderRow { // 其他字段定义 order_status: OrderStatus }
方案3:使用类型断言(临时兼容)
如果你确定 row.order_status 的取值一定在 chipColors 的键范围内,可以直接用类型断言跳过检查:
<Chip color={chipColors[row.order_status as keyof typeof chipColors]} text={row.order_status} />
方案4:添加运行时校验+兜底逻辑(兼容未知状态)
如果后端返回的状态可能新增,建议加一层判断和兜底,避免运行时出现异常:
const getChipColor = (status: string) => { if (status in chipColors) { return chipColors[status as keyof typeof chipColors] } return 'default' // 自定义兜底颜色 } // 组件内使用 <Chip color={getChipColor(row.order_status)} text={row.order_status} />
内容的提问来源于stack exchange,提问作者tickwave
相关产品推荐
相关产品推荐

