TypeScript Error: Index signature parameter type cannot be a union type
Hi everyone! I'm new to TypeScript and encountered a confusing error. I'm trying to create an object where keys can only be two string types: `'user'` or `'admin'`. I wrote this code:
```typescript
type Role = 'user' | 'admin';
interface UserData {
name: string;
age: number;
}
// Trying to create an object where the key is a role and the value is user data
const users: { [key: Role]: UserData } = {};
```
But TypeScript gives an error: *"An index signature parameter type cannot be a union type. Consider using a mapped object type instead"*. I understand that index signatures usually work with `string`, `number`, or `symbol`, but why can't I use a union of literal strings? They are still strings after all!
I need the `users` object to guaranteed contain onl
No answers yet.
Log in to leave an answer