GAZAR

Principal Engineer | Mentor

keyof in TypeScript

keyof in TypeScript

keyof is a TypeScript operator that returns a type that represents the union of all property names of a given type. In other words, it returns a type that represents the keys of an object. This can be used to create powerful type guards that can be used to enforce the structure of an object.

interface User {
  name: string;
  age: number;
  email: string;
}

type UserKeys = keyof User;

OR using it like

function processUser(user: { [key in keyof User]: any }) {}

keyof is a powerful tool in TypeScript that can be used to create powerful type guards that enforce the structure of an object. By using keyof, you can improve the type safety, maintainability, and reusability of your code. In this article, we've seen how to use keyof to create type guards that enforce the structure of an object. With keyof, you can write more robust and maintainable code.