Error "Element implicitly has an 'any' type" when accessing object by string key
Hello everyone! I'm new to TypeScript and encountered an error I can't understand. I have an object with predefined keys, and I want to get a value by a key that comes from a variable of type string.
Here's a simplified example:
```typescript
const userRoles = {
admin: 'full access',
editor: 'editing',
viewer: 'view only'
};
function getRole(roleName: string) {
return userRoles[roleName];
}
```
TypeScript throws an error:
```
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ admin: string; editor: string; viewer: string; }'.
No index signature with a parameter of type 'string' was found on type '{ admin: string; editor: string; viewer: string; }'.
```
I understand that the problem is in t
No answers yet.
Log in to leave an answer
Blogs