What does "keyof typeof" mean in TypeScript and how does it work?
Hi everyone! I recently started learning TypeScript and came across the `keyof typeof` construct, which appears in some code examples. I understand that `keyof` is used to get the keys of an interface or type, and `typeof` is used to get the type of a variable. But when they are combined together, I get confused.
For example, I have this code:
```typescript
const colors = {
red: '#ff0000',
green: '#00ff00',
blue: '#0000ff'
};
type ColorKeys = keyof typeof colors;
```
What is happening here? Why can't I just write `keyof colors`? And what exactly is the result? I tried using this in a function that takes an object key, but TypeScript complains about the types.
Can you explain in simple terms how the `keyof typeof` combination works and in what situations it's best to use it?
No answers yet.
Log in to leave an answer