0
0
Typescriptprogramming~3 mins

Why Keyof operator in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your code could instantly know all the valid property names without you typing them again?

The Scenario

Imagine you have an object with many properties, and you want to write code that works with these properties safely. Without a tool, you might write property names as plain strings everywhere.

For example, you want to get or check a property by name, but you have to type the property names manually each time.

The Problem

Typing property names manually is slow and risky. If you make a typo, your code might break, but you won't know until you run it.

Also, if the object changes (like adding or removing properties), you have to find and fix all those strings manually.

The Solution

The Keyof operator in TypeScript lets you get all the keys of an object type as a union of string literals.

This means you can write code that automatically knows the valid property names, so you get help from the editor and avoid mistakes.

Before vs After
Before
function getValue(obj: any, key: string) { return obj[key]; }
After
function getValue<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; }
What It Enables

It enables safer and smarter code that automatically adapts to object properties, reducing bugs and saving time.

Real Life Example

When building a form with many fields, you can use keyof to ensure you only access valid field names, preventing errors when reading or updating form data.

Key Takeaways

Typing property names manually is error-prone and hard to maintain.

Keyof operator extracts valid keys from object types automatically.

This leads to safer, cleaner, and more maintainable code.