0
0
Typescriptprogramming~15 mins

Keyof operator in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
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 values
Create a type alias ContactKeys using the keyof operator on the contact object type
Write a function getContactValue that takes the contact object and a key of type ContactKeys and returns the value of that key
Call 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
1
Create the contact object
Create a constant object called contact with these exact properties and values: name set to 'Alice', email set to 'alice@example.com', and phone set to '123-456-7890'.
Typescript
Need a hint?

Use const contact = { name: 'Alice', email: 'alice@example.com', phone: '123-456-7890' }.

2
Create a type alias using keyof
Create a type alias called ContactKeys that uses the keyof operator on the type of contact.
Typescript
Need a hint?

Use type ContactKeys = keyof typeof contact; to get keys of the contact object.

3
Write a function to get contact values by key
Write a function called getContactValue that takes two parameters: obj of the same type as contact, and key of type ContactKeys. The function should return the value of obj[key].
Typescript
Need a hint?

Define function getContactValue(obj: typeof contact, key: ContactKeys) { return obj[key]; }.

4
Call the function and print the email
Call getContactValue with contact and the key 'email'. Print the result using console.log.
Typescript
Need a hint?

Use console.log(getContactValue(contact, 'email')); to print the email.