Do you know about TypeScript keyof operator?

In TypeScript, the keyof operator creates a union type of all the known public property names of the given type.

To understand the actual use case of the keyof operator, let us consider the below example.

There is a type created with an interface,


interface IProduct {
    id: number;
    name: string;
    price: number;
    stock: number;
}

Now, you need to create a function to perform the below tasks:

  • Accepts type as input parameter
  • Accepts value to be updated for the given property of the type
  • The third and most crucial input property is the property name to be updated.

So, you need to write the function that accepts these three input parameters and ensure that the property name it accepts is valid for the type, in this case type is IProduct, so as the property name it should only accept,

  • Id
  • Name
  • Price
  • Stock

Any other property name should throw a compile time error.

To achieve that, you can use keyof operator to create a union type of all known properties of IProduct.


type ProductKey = keyof IProduct; // "id" | "name" | "price" | "stock" 

After creating a new type, you can create a function to update a particular property of IProduct type, as shown below:


function updateProductProperty<T extends ProductKey>(product: IProduct, property: T, value: any): IProduct {
    product[property] = value;
    return product;
}


The function uses a generic type parameter T that extends ProductKey.

 As you see above, the ProductKey type is defined as the keyof IProduct,  which means it can be the property name of the IProduct interface. By extending ProductKey, T is constrained to only those types, ensuring that the property parameter can only be a valid property name of the IProduct.

Now, when you use the above function and pass wrong property name , TypeScript gives compile time error.


let p: IProduct = { 
    id: 1, 
    name: "Product 1", 
    price: 100, 
    stock: 10 
};
updateProductProperty(p, "price", 200);
updateProductProperty(p, "dj", 20);


So, now you understand where the TypeScript keyof operator can be beneficial.  I hope you find this post useful. Thanks for reading.


Discover more from Dhananjay Kumar

Subscribe to get the latest posts sent to your email.

Published by Dhananjay Kumar

Dhananjay Kumar is founder of NomadCoder and ng-India

Leave a comment

Discover more from Dhananjay Kumar

Subscribe now to keep reading and get access to the full archive.

Continue reading