TypeScript: 通过字符串键访问对象时出现“Element implicitly has an 'any' type”错误
大家好!我是 TypeScript 新手,遇到了一个无法解决的问题。我写了一个函数,它接受一个包含用户数据的对象和一个字符串——状态。需要返回具有该状态的用户数组。
这是我的代码:
```typescript
interface User {
name: string;
status: 'active' | 'inactive' | 'pending';
}
const usersByStatus: Record = {
active: [{ name: 'Иван', status: 'active' }],
inactive: [{ name: 'Мария', status: 'inactive' }],
pending: [{ name: 'Петр', status: 'pending' }],
};
function getUsersByStatus(status: string): User[] {
return usersByStatus[status];
}
```
TypeScript 报错:
> Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Record'. No index signature with a parameter of type 'string' was found on type 'Record'.
我不明白为什么会出错。因为 `Record` 应该接受任何