Using the Keyof Operator in TypeScript
📖 Scenario: You are working on a simple contact management app. You have a contact object with details like name, email, and phone number.You want to create a function that can get the value of any property of the contact by using the property name safely.
🎯 Goal: Build a TypeScript program that uses the keyof operator to restrict the property names you can use to get values from a contact object.
📋 What You'll Learn
Create a contact object with exact properties:
name, email, and phone with given valuesCreate a type alias
ContactKeys using the keyof operator on the contact object typeWrite a function
getContactValue that takes the contact object and a key of type ContactKeys and returns the value of that keyCall
getContactValue with the contact object and the key 'email' and print the result💡 Why This Matters
🌍 Real World
Using the <code>keyof</code> operator helps you write safer code when working with objects, avoiding mistakes like typos in property names.
💼 Career
Many TypeScript jobs require understanding how to use advanced types like <code>keyof</code> to build reliable and maintainable codebases.
Progress0 / 4 steps