0
0
Typescriptprogramming~5 mins

Keyof operator in Typescript

Choose your learning style9 modes available
Introduction

The keyof operator helps you get all the property names of an object type as a union of string literal types. It makes working with object keys easier and safer.

When you want to get all keys of an object type to use them elsewhere.
When you want to make sure a variable can only be one of the keys of an object.
When you want to create functions that work with object keys without hardcoding them.
When you want to avoid mistakes by using actual keys from an object type instead of strings.
When you want to build flexible and reusable code that adapts to object shapes.
Syntax
Typescript
type Keys = keyof ObjectType;

ObjectType is any object type you want to get keys from.

The result Keys is a union of string literal types representing the keys.

Examples
This gets the keys 'name' and 'age' from the Person type.
Typescript
type Person = { name: string; age: number; };
type PersonKeys = keyof Person;  // 'name' | 'age'
You can only assign keys that exist in the object type.
Typescript
const key: keyof Person = 'name';  // valid
// const wrongKey: keyof Person = 'height';  // error
This function safely gets a value from an object using a key that must exist on the object.
Typescript
function getValue<T, K extends keyof T>(obj: T, key: K) {
  return obj[key];
}
Sample Program

This program defines a Car type and a function that prints a property of a car. The function only accepts keys that exist on Car. It then prints the make and year of the car.

Typescript
type Car = {
  make: string;
  model: string;
  year: number;
};

function printCarProperty(car: Car, key: keyof Car) {
  console.log(`The car's ${key} is ${car[key]}`);
}

const myCar: Car = { make: 'Toyota', model: 'Corolla', year: 2020 };

printCarProperty(myCar, 'make');
printCarProperty(myCar, 'year');
OutputSuccess
Important Notes

The keyof operator works only on object types, not on primitive types.

Using keyof helps catch errors early by restricting keys to valid ones.

Summary

keyof gets all keys of an object type as a union of strings.

It helps write safer and clearer code by limiting keys to valid ones.

Commonly used in generic functions to work flexibly with object properties.