Questions
What are the `keyof` and `typeof` operators and how do you use them in TypeScript?
The Scenario
You are a frontend engineer at a social media company. You are writing a new function that needs to take an object and a key of that object, and return the value of that key.
You want to make sure that the function is type-safe and that you can only pass valid keys of the object to the function.
The Challenge
Explain what the keyof and typeof operators are in TypeScript and how you would use them to solve this problem.
A junior engineer might not be aware of the `keyof` and `typeof` operators. They might try to solve this problem by using a string to represent the key, which would not be type-safe.
A senior engineer would know that the `keyof` and `typeof` operators are the perfect tools for this job. They would be able to explain what these operators are and how to use them to create a type-safe function that can get a property of an object.
Step 1: Understand What the keyof and typeof Operators Are
| Operator | Description |
|---|---|
keyof | An operator that takes an object type and returns a string or numeric literal union of its keys. |
typeof | An operator that takes a value and returns its type. |
Step 2: Solve the Problem
Here’s how we can use the keyof and typeof operators to create a type-safe function that can get a property of an object:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const myObject = {
a: 1,
b: 2,
c: 3
};
const myValue = getProperty(myObject, "a"); // 1In this example, we use the keyof operator to get a union of the keys of the myObject object. We then use this union as a generic constraint on the key parameter to make sure that we can only pass valid keys of the object to the function.
We use the typeof operator to get the type of the myObject object, which is then used as the type of the obj parameter.
Practice Question
You want to create a new type that is a union of the keys of an existing type. Which of the following would you use?