🔷 TypeScript Q11 / 101

What is keyof keyword?

AI-Powered Answer ✓ Answered

In TypeScript, the `keyof` type query operator is a powerful tool for working with object types in a type-safe manner. It allows you to extract the union type of all public property keys (strings or symbol literals) of a given type.

What is `keyof`?

The keyof operator takes an object type and produces a string or symbol literal union type that represents all known, public property names of that object type. This is incredibly useful for creating generic functions that need to work with specific properties of an object while maintaining type safety.

Syntax

The syntax is straightforward: keyof Type

Example Usage

Consider a simple interface:

typescript
interface Person {
  name: string;
  age: number;
  occupation: string;
}

type PersonKeys = keyof Person; // 'name' | 'age' | 'occupation'

In this example, PersonKeys will be a union type consisting of the literal strings 'name', 'age', and 'occupation'. This means any variable typed as PersonKeys can only hold one of these specific string values, enforcing type safety.

One of the most common and powerful uses of keyof is in conjunction with generic types to create type-safe property accessors:

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

interface Product {
  id: number;
  name: string;
  price: number;
}

const product: Product = { id: 1, name: 'Laptop', price: 1200 };

const productName = getProperty(product, 'name'); // Type: string
const productPrice = getProperty(product, 'price'); // Type: number

// const invalidProperty = getProperty(product, 'description'); 
// Error: Argument of type '"description"' is not assignable to parameter of type 'keyof Product'.

Here, K extends keyof T ensures that the key argument must be a valid property name of the obj argument. T[K] is a 'lookup type' (or 'indexed access type') which means the return type of getProperty will be the type of the property specified by key on obj.

Benefits of `keyof`

  • Type Safety: Prevents runtime errors caused by trying to access non-existent properties.
  • Improved Readability: Makes code more explicit about which properties are expected.
  • Better Autocompletion: IDEs can suggest valid property keys, improving developer experience.
  • Refactoring Safety: If property names change in the original type, TypeScript will flag errors where keyof is used, helping maintain consistency.
  • Dynamic Property Access: Enables type-safe generic functions that operate on object properties dynamically.

Interaction with Index Signatures

When an object type has an index signature, keyof will return the type of the index signature's key. For example:

typescript
interface MyDictionary {
  [key: string]: any;
  name: string;
}

type DictionaryKeys = keyof MyDictionary; // string | 'name'

interface MyNumberDictionary {
  [key: number]: string;
}

type NumberDictionaryKeys = keyof MyNumberDictionary; // number

If a type only has a string index signature, keyof will return string. If it has a number index signature, keyof will return number.