The keyof operator helps you get all the property names of an object type as a union of string literal types. It makes working with object keys easier and safer.
When you want to get all keys of an object type to use them elsewhere.
When you want to make sure a variable can only be one of the keys of an object.
When you want to create functions that work with object keys without hardcoding them.
When you want to avoid mistakes by using actual keys from an object type instead of strings.
When you want to build flexible and reusable code that adapts to object shapes.
Syntax
Typescript
type Keys = keyof ObjectType;
ObjectType is any object type you want to get keys from.
The result Keys is a union of string literal types representing the keys.
Examples
This gets the keys 'name' and 'age' from the Person type.
Typescript
type Person = { name: string; age: number; };
type PersonKeys = keyof Person; // 'name' | 'age'
You can only assign keys that exist in the object type.
Typescript
const key: keyof Person = 'name'; // valid// const wrongKey: keyof Person = 'height'; // error
This function safely gets a value from an object using a key that must exist on the object.
Typescript
function getValue<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
Sample Program
This program defines a Car type and a function that prints a property of a car. The function only accepts keys that exist on Car. It then prints the make and year of the car.
Typescript
type Car = {
make: string;
model: string;
year: number;
};
function printCarProperty(car: Car, key: keyof Car) {
console.log(`The car's ${key} is ${car[key]}`);
}
const myCar: Car = { make: 'Toyota', model: 'Corolla', year: 2020 };
printCarProperty(myCar, 'make');
printCarProperty(myCar, 'year');
OutputSuccess
Important Notes
The keyof operator works only on object types, not on primitive types.
Using keyof helps catch errors early by restricting keys to valid ones.
Summary
keyof gets all keys of an object type as a union of strings.
It helps write safer and clearer code by limiting keys to valid ones.
Commonly used in generic functions to work flexibly with object properties.
Practice
(1/5)
1. What does the keyof operator do in TypeScript?
easy
A. It returns the values of an object as a union type.
B. It converts a type to a string literal type.
C. It creates a union type of all keys of an object type.
D. It extracts the type of a function's return value.
Solution
Step 1: Understand the purpose of keyof
The keyof operator takes an object type and produces a union of its keys as string literal types.
Step 2: Compare options with definition
Only "It creates a union type of all keys of an object type." correctly describes this behavior. The other options describe unrelated TypeScript features.
Final Answer:
It creates a union type of all keys of an object type. -> Option C
Quick Check:
keyof = union of keys [OK]
Hint: Remember: keyof lists keys, not values or types [OK]
Common Mistakes:
Confusing keyof with getting values
Thinking it returns runtime keys instead of types
Mixing it up with return type extraction
2. Which of the following is the correct syntax to get keys of type Person using keyof?
easy
A. type Keys = Person.keyof;
B. type Keys = keyof(Person);
C. type Keys = keys<Person>;
D. type Keys = keyof Person;
Solution
Step 1: Recall correct keyof syntax
The correct syntax is keyof TypeName without parentheses or dot notation.
Step 2: Evaluate each option
type Keys = keyof Person; uses correct syntax. type Keys = keyof(Person); incorrectly uses parentheses. type Keys = keys<Person>; uses a non-existent keys keyword. type Keys = Person.keyof; uses invalid dot notation.
Final Answer:
type Keys = keyof Person; -> Option D
Quick Check:
Correct syntax = keyof Type [OK]
Hint: Use keyof TypeName without parentheses [OK]
Common Mistakes:
Adding parentheses around the type
Using dot notation like Type.keyof
Confusing keyof with keys
3. Given the code:
type Car = { make: string; model: string; year: number };
type CarKeys = keyof Car;
let key: CarKeys = 'year';
console.log(key);
What is the output when this code runs?
medium
A. 'year'
B. 'make'
C. Error: Type 'string' is not assignable
D. undefined
Solution
Step 1: Understand keyof usage
CarKeys is a union of keys: 'make' | 'model' | 'year'. The variable key is assigned the string 'year', which is valid.
Step 2: Check console output
The console logs the value of key, which is 'year'. No errors occur.
Final Answer:
'year' -> Option A
Quick Check:
Assigned key = 'year' [OK]
Hint: Assign only keys from the union to avoid errors [OK]
Common Mistakes:
Expecting runtime error for type assignment
Confusing keys with values
Thinking keyof returns values
4. Identify the error in this code:
type User = { id: number; name: string };
function getValue(obj: User, key: keyof User) {
return obj.key;
}
medium
A. Using dot notation with variable key instead of bracket notation.
B. Missing return type annotation in function.
C. Incorrect type for parameter obj.
D. keyof User is not a valid type.
Solution
Step 1: Analyze property access in function
The function tries to access obj.key. Since key is a variable, dot notation looks for a property literally named 'key'.
Step 2: Correct property access syntax
To use a variable key, bracket notation obj[key] is required to access the dynamic property.
Final Answer:
Using dot notation with variable key instead of bracket notation. -> Option A
Quick Check:
Use obj[key] for dynamic keys [OK]
Hint: Use bracket notation for variable keys [OK]
Common Mistakes:
Using dot notation with variable keys
Ignoring TypeScript error messages
Assuming keyof is invalid
5. How can you write a generic function that takes an object and a key of that object, then returns the value of that key safely using keyof? Choose the correct implementation.
hard
A. function getProp<T>(obj: T, key: keyof T): string { return obj[key]; }
B. function getProp(obj: T, key: K): T[K] { return obj[key]; }
C. function getProp<T>(obj: T, key: string): any { return obj.key; }
D. function getProp(obj: T, key: K): K { return obj[key]; }
Solution
Step 1: Understand generic constraints with keyof
To ensure the key is valid for the object, the key type K must extend keyof T. This restricts keys to valid property names.
Step 2: Check return type and access
The return type should be T[K], the type of the property at key K. Accessing obj[key] returns this value safely.
Step 3: Evaluate options
function getProp(obj: T, key: K): T[K] { return obj[key]; } correctly uses generics and keyof. function getProp<T>(obj: T, key: string): any { return obj.key; } uses string key and dot notation, which is unsafe. function getProp<T>(obj: T, key: keyof T): string { return obj[key]; } fixes key type but wrongly fixes return type to string. function getProp(obj: T, key: K): K { return obj[key]; } lacks constraint on K and returns wrong type.
Final Answer:
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } -> Option B
Quick Check:
Generic key constrained by keyof = safe access [OK]
Hint: Use K extends keyof T and return T[K] [OK]
Common Mistakes:
Not constraining key type with keyof
Using string keys without type safety
Returning wrong or fixed types
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.