TypeScript Error: "An index signature parameter type cannot be a union type" — how to fix?
Hello, colleagues! I'm new to TypeScript and encountered an error I can't understand. There is an object that stores settings for different user types: 'admin' and 'user'. I want to create a type that ensures the object keys are only these strings and the values are boolean. Here is my code:
```typescript
type UserRole = 'admin' | 'user';
interface Settings {
[key: UserRole]: boolean; // Error!
}
```
TypeScript says: "An index signature parameter type cannot be a union type. Consider using a mapped object type instead". I thought union types could be used as keys, but the compiler disagrees. I need the object to only contain properties 'admin' and 'user', and when trying to access another key (e.g., 'guest'), TypeScript should throw an error. How to do this correctly? I saw that mapped types are mentioned in the documentation, but I don't fully understand how to apply them in my case. I would be grateful for a clear explanation with examples.
No answers yet.
Log in to leave an answer
Blogs
Security of Go Applications: Top 10 Vulnerabilities and How to Avoid Them
SOLID Principles in Kotlin: Theory and Practice for Clean Code
Caching in Rust: Redis, Memcached, and Built-in Solutions (Advanced Level)
CI/CD pipeline for Java: setup from scratch to not fear deployment