TypeScript Keyof

Learn via video courses
Topics Covered

Overview

In this article, we will get an insight into the keyof operator used in TypeScript. Like object.keys in JavaScript, the keyof operator has the equivalent concept in TypeScript. Although they have similar functioning, keyof only works on the type level and returns a literal union type but object.keys returns values. The keyof operator takes an object type and returns a string or numeric literal union of its keys.

Introduction

The keyof operator was introduced in TypeScript 2.1s. This keyword has become a building block for advanced typing in TypeScript and it is used very often in the code. It is referred to as the index query operator because the keyword queries the type specified after keyof. The indexed base type query fetches the values from properties and their attributes that are related to elements like default keywords and their data types.

Defining the KeyOf Operator

In TypeScript, the keyof operator is used to fetch the user values. It is majorly used in Generics and follows the format of a union operator and its properties. It retrieves the index for the values that are specified by the users. This operator can be used in objects like collections, and classes that are used to store and retrieve data using key and value pairs. Using the map instance object.keys() method, we can fetch the keys that are stored in the memory.

Syntax

In the above snippet, we have created a class with a name and used a var or let data type with the variable name and called the DemoClass with the keyof operator. When the value is assigned to the variable name, it will display on the output screen.

Using KeyOf with TypeScript generics

The TypeScript keyof operator is used to apply constraints in a generic function.

Example

The above-given function retrieves the type of object property defined using generics. keyof T returns a union of string literal types. Literals are defined as the constant values that are assigned to the constant variables.

K is a string literal type so we use extends keyword to apply constraints on K. The indexed operator obj[key] returns the same type that the property will have.

Now we will see how the getProperty type used below:

The compiler will validate the key to match one of the property names of type T as we have applied the type constraints for the second parameter. The compilation error will occur if we try to pass an invalid key sal.

We can define a union type manually when we don't use the keyof operator:

Although the same kind of constraint is applied, the manual approach is less maintainable. The definition of type will be duplicated and the change of the original type will not be automatically generated.

Using KeyOf with TypeScript mapped Types

We can use the TypeScript keyof operator with mapped types that converts the existing types with new types by iterating through keys. Mapped types are built on index signatures that are used to define the types of properties that have not been declared already.

Example

Here is an example to transform the FeatureFlags type using the OptionsFlags mapped type.

Output

In the above snippet, OptionsFlags is defined as a generic type that involves a type parameter T. Property in keyof T defines the iteration of the property names of type T, and the square bracket indicates the index signature syntax. Therefore, the OptionsFlags will remap the values to boolean type and contains all the properties of type T.

KeyOf with Explicit keys

The TypeScript keyof operator creates a union type when we use the keyword on an object type with explicit keys.

Example

Output

KeyOf with Index Signatures

The TypeScript keyof operator can be used with index signatures to remove the index type. Index signatures are used to represent the type of object where the values of the object are of consistent types.

Example

Using KeyOf Conditional Mapped Types

Conditional types are used to choose between two declared types based on a conditional expression. When we used keyof with TypeScript mapped types, we mapped all the properties to the boolean type. Now, we will perform conditional type mapping to use conditional types.

Example

Output

In the above snippet, we have mapped the non-function properties to the boolean types. All the future changes made in the FeatureFlags type will get reflected in the Features type automatically.

Using Keyof with Utility Types

Utility types are the set of inbuilt mapped types.

Example

In the above snippet, the Record is a utility type that returns a new type after mapping all the property keys to type T.

We can make use of the Record type to rewrite the previous FeatureOptions type.

Output

In the above snippet, we got the same Features type using the Record type to have a set of properties and transform the Features type's properties to a boolean type.

We can also use the keyof operator with the Pick type. This type allows you to pick single or multiple properties from an object type and generate a new type with chosen properties.

The keyof operator guarantee that the constraint is applied as only valid property names will get passed to the second parameter K.

Conclusion

  • This operator is small but can create a critical cog in the TypeScript machine.
  • When we use keyof with other tools in TypeScript, we can provide well-constrained types to enhance type safety in the code.
  • The keyof type annotation is used to take out the keys from an object.
  • Using the object.keys() method, we can retrieve key indexes and their values. Users can easily retrieve data while working on bi-enterprise applications.
  • In this article, we were able to use the keyof operator with TypeScript generics, TypeScript mapped types, Explicit keys, Index signatures, Conditional mapped types, and Utility types.
  • Hope this article has provided you with the relevant information related to the keyof keyword and its importance in the TypeScript code.