TypeScript keyof

TypeScript tutorial

🔑 TypeScript keyof

In TypeScript keyof keyword  is used to get a union of property names (keys) of an object type.

📌 Think of keyof as:
“Give me all the keys of this type”


1️⃣ Basic keyof Example

type User = {
id: number;
name: string;
age: number;
};
type UserKeys = keyof User;

UserKeys becomes:

"id" | "name" | "age"

2️⃣ Using keyof with Variables

let key: keyof User;

key = “id”; // ✅
key = “name”; // ✅
key = “email”; // ❌ Error

✔ Prevents invalid property access


3️⃣ keyof with Functions (Very Common ⭐)

function getValue<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
const user = {
id: 1,
name: “Sanjit”,
age: 25
};getValue(user, “name”); // ✅
getValue(user, “email”); // ❌ Error

👉 This is type-safe property access


4️⃣ keyof + typeof (Real-World Usage)

const settings = {
theme: "dark",
fontSize: 14,
isAdmin: true
};
type SettingsKeys = keyof typeof settings;

Result:

"theme" | "fontSize" | "isAdmin"

📌 typeof → gets type of variable
📌 keyof → gets keys of that type


5️⃣ keyof with Interfaces

interface Product {
id: number;
name: string;
price: number;
}
type ProductKeys = keyof Product;

Same result as object type.


6️⃣ keyof with Index Signatures

type Scores = {
[key: string]: number;
};
type ScoreKey = keyof Scores;

Result:

string | number

📌 Because JavaScript object keys can be strings or numbers.


7️⃣ keyof vs Hardcoded Strings ❌

❌ Bad:

function read(obj: any, key: string) {
return obj[key];
}

✅ Good:

function read<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}

✔ Compile-time safety
✔ Auto-complete support


8️⃣ Practical Example (Update Function)

function updateField<T, K extends keyof T>(
obj: T,
key: K,
value: T[K]
) {
obj[key] = value;
}
updateField(user, “age”, 30); // ✅
updateField(user, “age”, “30”); // ❌ Error

🔑 keyof Summary

Concept Meaning
keyof T Union of keys
With typeof Keys of variables
With generics Safe property access
With functions Prevent bugs

⭐ Best Practices

✔ Use keyof for safe object access
✔ Combine with generics
✔ Avoid hardcoded string keys
✔ Very useful in utility functions & APIs

You may also like...