Open In App

Typescript Keyof Type Operator

Last Updated : 22 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The TypeScript keyof operator is used to get a union of all keys in an object type. It’s useful when you want to work with the property names of an object in a type-safe way, ensuring only valid keys are used.

We can use it to define generic functions that work with any object type, without knowing the specific keys of that type. It can also be used to create read-only versions of an interface or to extract specific keys from an interface.

Syntax

type KeysOfType = keyof ObjectType;

How to use the Keyof Type Operator? 

We have defined an interface “Person” with three different properties: name, age, and gender. We then define a type PersonKeys that is equal to keyof Person, which is a union type of “name” | “age” | “gender”.

interface Person {
      name: string;
      age: number;
      gender: string;
}
type PersonKeys = keyof Person;

Examples Showing Keyof Type Operator

Let’s look at some examples of Keyof type operator in TypeScript. These examples will help you understand the working of Keyof type operator.

1. Accessing object properties

Example: In this example, we define an interface Person with three properties: name, age, and gender. We also define a variable person of type Person with some values.

JavaScript
interface Person {
    name: string;
    age: number;
    gender: string;
}

const person: Person = {
    name: "John",
    age: 25,
    gender: "male",
};

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

console.log(getProperty(person, "name")); // "John"
console.log(getProperty(person, "age")); // 25
console.log(getProperty(person, "gender")); // "male"

Output: 

John
25
male

Explanation:

  • getProperty takes an object obj of type T and a key K, where K is a valid key of T.
  • K extends keyof T, ensuring the key exists in the object.
  • The function returns the value associated with obj[key].

2. Using mapped Type:

Example: In this example, we have defined an interface Person with three properties: name, age, and gender.

JavaScript
interface Person {
    name: string;
    age: number;
    gender: string;
}

type ReadonlyPerson = {
    readonly [K in keyof Person]: Person[K];
}

const person: ReadonlyPerson = {
    name: "John",
    age: 25,
    gender: "male",
};

console.log(person.name); // "John"
console.log(person.age); // 25
console.log(person.gender); // "male"

Output:

John
25
male

Explanation:

  • [K in keyof Person] creates properties with keys K and value types Person[K], but read-only.
  • The type ReadonlyPerson has immutable properties derived from Person.
  • A ReadonlyPerson variable cannot modify its properties.


Next Article

Similar Reads