Tip - TypeScript keyof operator

typescript
Back

Example

Lets say we have Product type with below keys

interface IProduct {
id: string;
title: string;
base_price: number;
selling_price: number;
dateAdded: Date;
}
type ProductKey = keyof Product;
// "id" | "title" | "base_price" | "selling_price" | "dateAdded"

Then while using it

const iPhone: IProduct = {
id: "AberWdsdXps",
title: "iPhone 12 (Red)",
base_price: 12000,
selling_price: 10000,
dateAdded: new Date(),
};
const getValue = (key: ProductKey) => iPhone[key];

Thanks.

MIT © Mohan Dere.
-