# The keyof Operator

> Extracting the keys of an object into a literal union type.

Subject: TypeScript | Lesson 13 of 54 | 3 min read
Interactive lesson: https://codewithanimation.in/typescript/keyof-operator
Previous: [The typeof Operator](https://codewithanimation.in/typescript/typeof-operator.md) | Next: [Control Flow & Type Guards](https://codewithanimation.in/typescript/control-flow-type-guards.md)

## Extracting object keys

The `keyof` operator takes an object type and produces a string (or numeric) literal union of its keys.

If you have an object type with properties `id` and `name`, `keyof` will generate the union type `'id' | 'name'`.

## Dynamic but safe property access

Imagine writing a `getProperty` function. You want the user to pass in an object and a key, and return the value.

If you type the key as `string`, the user could pass `'randomKey'`, and TypeScript wouldn't complain. By typing the key as `keyof MyObject`, TypeScript will strictly enforce that they only pass valid keys.

## Using keyof

```typescript
type User = {
  id: number;
  name: string;
  isActive: boolean;
};

type UserKeys = keyof User;
// Result: "id" | "name" | "isActive"

let key: UserKeys = "name"; // OK
key = "email"; // Error!
```

## Common mistake: keyof typeof

A common beginner mistake is trying to use `keyof` directly on a JavaScript object variable.

```typescript
const user = { name: "Alice" };

// Error: 'user' refers to a value, but is being used as a type.
type Key = keyof user;
```

Because `keyof` only works on Types, you must first convert the value to a type using `typeof`.

`type Key = keyof typeof user; // OK`

## Tip: Index Signatures

If you use `keyof` on a type with a string index signature (like `{[key: string]: any}`), it will return `string | number`. This is because in JavaScript, object keys are always coerced to strings, so `obj[0]` is the same as `obj["0"]`.

## Try it: Try it

Watch how `keyof` extracts the property names from an interface and assembles them into a literal union type.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/typescript/keyof-operator

## Check yourself

### Question 1

If you have a JavaScript object 'const settings = { theme: "dark" }', how do you extract its keys into a union type?

- A. type Keys = keyof settings;
- B. type Keys = typeof keyof settings;
- C. type Keys = keyof typeof settings;

Correct answer: C

You must first use 'typeof' to extract the type shape from the JavaScript variable, and then apply 'keyof' to that type shape.

- Why not A: You cannot use keyof directly on a value.
- Why not B: The order is backwards.

## Remember this

- `keyof` extracts the keys of a type into a literal union.
- It is essential for safely typing dynamic property access.
- To extract keys from a JS object, use `keyof typeof obj`.
- It extracts keys, not values.
