TypeScript keyof
🔑 TypeScript keyof
📌 Think of
keyofas:
“Give me all the keys of this type”
1️⃣ Basic keyof Example
UserKeys becomes:
2️⃣ Using keyof with Variables
✔ Prevents invalid property access
3️⃣ keyof with Functions (Very Common ⭐)
👉 This is type-safe property access
4️⃣ keyof + typeof (Real-World Usage)
Result:
📌 typeof → gets type of variable
📌 keyof → gets keys of that type
5️⃣ keyof with Interfaces
Same result as object type.
6️⃣ keyof with Index Signatures
Result:
📌 Because JavaScript object keys can be strings or numbers.
7️⃣ keyof vs Hardcoded Strings ❌
❌ Bad:
✅ Good:
✔ Compile-time safety
✔ Auto-complete support
8️⃣ Practical Example (Update Function)
🔑 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
