如何修复 TypeScript 中启用 noImplicitAny 标志时的“对象类型的索引签名隐式具有 'any' 类型”错误
大家好!我正在用 TypeScript 写一个项目,并启用了带有 `noImplicitAny` 标志的严格模式。现在我遇到了一个问题:当我尝试通过动态键访问对象时,编译器会报错:
> 元素隐式具有 'any' 类型,因为类型为 'string' 的表达式不能用于索引类型 '...'。在类型 '...' 上未找到带有类型为 'string' 的参数的索引签名。
这是我的代码示例。我有一个包含不同订单状态颜色的配置对象:
```typescript
const statusColors = {
pending: 'orange',
confirmed: 'blue',
shipped: 'green',
cancelled: 'red'
};
function getStatusColor(status: string): string {
return statusColors[status]; // ❌ 错误!
}
```
我期望函数能根据键返回颜色,但 TypeScript 报错了。我明白问题在于 `status` 的类型是 `string`,而对象的键是具体的字面量(`'pending'`、`'confirmed'` 等)。但如何正确地为这种情况进行类型化?我不想