Open In App

Typescript Keyof Type Operator

Last Updated : 11 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript, the keyof operator is used to extract the keys of a type as a union type. It is a type operator that allows you to access the keys of an object type or an interface.

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: 

keyof type operator example

Accessing object properties using the Keyof Type Operator

Explanation:

We have defined a function getProperty that takes an object obj of type T and a key of type K, where K extends keyof T. It means that key must be one of the keys of the object obj. Inside the getProperty function, we have simply returned the value of 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:

keyof type operator with mapped types example output

Using Keyof Type Operator with mapped types

Explanation:

The syntax [K in keyof Person] means that for each key K in the Person interface, we have created a new property with the same key K and the same value type Person[K], but with the read-only modifier. We have then defined a variable person of type ReadonlyPerson with some values. Since a person is of type ReadonlyPerson, we cannot modify its properties.



Similar Reads

Difference Between valueof and keyof in TypeScript
In this article, we are going to learn the difference between valueOf() and keyof in TypeScript. ValueOf() methodThe valueOf() method in TypeScript is used to return the primitive value of the specified number object. Syntax:number.valueOf();Example 1: In this example, we have used the ValueOf() method. C/C++ Code // valueOf() let num = new Number(
2 min read
TypeScript in operator narrowing Type
In this article, we will learn about the 'in' operator narrowing Type in Typescript. In TypeScript, the 'in' operator is used to narrow or refine the type of an object within a conditional statement or block. It checks whether a specific property or key exists within an object, and if it does, it narrows the type of that object to include that prop
3 min read
TypeScript Non-null Assertion Operator (Postfix !) Type
TypeScript non-null assertion operator (!) is used to assert that a value is non-null and non-undefined, even when TypeScript's strict null checks are enabled. This operator tells TypeScript to treat the expression as if it's guaranteed to have a value, eliminating compile-time null and undefined checks. Syntaxconst nonNullValue: Type = value!;Para
2 min read
Typescript Required&lt;Type&gt; Utility Type
In this article, we are going to learn about the Required&lt;Type&gt; in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. One of the features of Typescript is Required&lt;Type&gt; which is a built-in utility type that allows you to create a new type that makes all properties of the origina
4 min read
Typescript Record&lt;Keys, Type&gt; Utility Type
In this article, we are going to learn about the Record&lt;Keys, Type&gt; in Typescript. TypeScript is a programming language that is a strict syntactical superset of JavaScript. It adds optional static typing and class-based object-oriented programming to JavaScript, one of the features is Record&lt;Keys, Type&gt; which is a built-in utility type
4 min read
Typescript Partial&lt;Type&gt; Utility Type
In this article, we are going to learn about the Partial&lt;Type&gt; that is available in the Typescript. One of the features in Typescript is Partial&lt;Type&gt; which is a built-in utility type. It helps to create a new type by making all properties of an existing type optional. Now we can pass properties of an object of a new type that is create
4 min read
Typescript Awaited&lt;Type&gt; Utility Type
In this article, we are going to learn about the Awaited&lt;Type&gt; in TypeScript. It is a programming language that is a strict syntactical superset of JavaScript. It adds optional static typing and class-based object-oriented programming to JavaScript, one of the features of the typescript is Awaited&lt;Type&gt; it is a utility type in TypeScrip
2 min read
TypeScript Omit&lt;Type, Keys&gt; Utility Type
In this article, we are going to learn about the Omit&lt;Type, Keys&gt; utility type in Typescript. TypeScript is a powerful language that provides many utility types to make development easier and more efficient. One of the Typescript features is Omit utility type. We can use it when, let's say there exists a type already but we want to create a n
4 min read
TypeScript Pick&lt;Type, Keys&gt; Utility Type
In this article, we are going to learn about the Pick&lt;Type, Keys&gt; utility type in TypeScript. TypeScript is a programming language that is a strict syntactical superset of JavaScript. It adds optional static typing and class-based object-oriented programming to JavaScript, Pick&lt;Type, Keys&gt; is one of the features of Typescript which is a
5 min read
TypeScript Extract&lt;Type, Union&gt; Utility Type
In this article, we are going to learn about Extract&lt;Type, Union&gt; utility type in TypeScript, TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tools at any scale. Extract&lt;Type, Union&gt; utility type is used to extract a subset of types from a union type that matches a certain criterion, This
4 min read