CodeWithMihir

TypeScript Tutorial

TypeScript keyof Operator Explained

Learn how the keyof operator works in TypeScript, including object keys, safe property access, generic helpers, and practical examples.

Welcome back! I am Mihir, and in this lesson we will learn the keyof operator in TypeScript.

keyof creates a union of the property names of a type.


Basic keyof Example

type User = {
  id: number;
  name: string;
  email: string;
};

type UserKeys = keyof User;

UserKeys becomes:

"id" | "name" | "email"

Using keyof with Variables

let key: keyof User;

key = "id";
key = "name";

Invalid:

key = "age";

age is not a key of User.


Safe Property Access

function getUserValue(user: User, key: keyof User) {
  return user[key];
}

const user: User = {
  id: 1,
  name: "Mihir",
  email: "mihir@example.com",
};

const value = getUserValue(user, "name");

The key must be one of the real properties.


keyof with Generics

function getProperty<T, K extends keyof T>(object: T, key: K): T[K] {
  return object[key];
}

This is a very common TypeScript pattern.

Usage:

const product = {
  id: 101,
  name: "Keyboard",
  price: 2500,
};

const productName = getProperty(product, "name");

productName is inferred as string.


keyof with Interfaces

interface Settings {
  theme: string;
  notifications: boolean;
}

type SettingsKey = keyof Settings;

This becomes:

"theme" | "notifications"

keyof with Index Signatures

type Scores = {
  [username: string]: number;
};

type ScoreKeys = keyof Scores;

For string index signatures, the key type is usually:

string | number

JavaScript object keys are converted to strings, so TypeScript reflects that behavior.


Why keyof Is Useful

keyof helps you:

  • restrict keys to valid property names
  • build safer helper functions
  • avoid typo-prone string keys
  • create advanced utility types
  • connect object keys to object values

Quick Recap

  • keyof creates a union of property names.
  • It works with type aliases and interfaces.
  • keyof User might become "id" | "name" | "email".
  • K extends keyof T creates safe generic key access.
  • T[K] gives the value type for a specific key.

Next up, we will learn Generic Utility Patterns →.