Bird
Raised Fist0
Typescriptprogramming~10 mins

Keyof operator in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Keyof operator
Define Interface
↓
Apply keyof Operator
↓
Get Union of Keys
↓
Use Keys as Type
↓
Access Object Properties Safely
The keyof operator takes an object type and produces a union of its keys as string literal types.
Execution Sample
Typescript
interface Person {
  name: string;
  age: number;
}
type PersonKeys = keyof Person;
let key: PersonKeys = "name";
This code defines an interface Person, then uses keyof to get a union of its keys, and assigns a valid key to a variable.
Execution Table
StepActionEvaluationResult
1Define interface Person with keys 'name' and 'age'Person = {name: string, age: number}Interface created
2Apply keyof Personkeyof Person"name" | "age" (union type)
3Declare variable key of type PersonKeyskey: "name" | "age"Variable declared
4Assign "name" to keykey = "name"Valid assignment
5Try assign "height" to keykey = "height"Error: Type '"height"' is not assignable to type '"name" | "age"'
💡 Execution stops because "height" is not a valid key of Person, causing a type error.
Variable Tracker
VariableStartAfter Step 4After Step 5
keyundefined"name"Error (invalid assignment)
Key Moments - 2 Insights
Why can't I assign a string like "height" to the variable key?
Because keyof Person only allows keys that exist in Person, which are "name" and "age" (see execution_table step 5). "height" is not part of that union type.
What does keyof actually produce?
It produces a union of string literal types representing the keys of the object type (see execution_table step 2).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the type of PersonKeys after step 2?
Anumber
Bstring
C"name" | "age"
Dany
💡 Hint
Check the 'Evaluation' column in step 2 of the execution_table.
At which step does the assignment cause a type error?
AStep 5
BStep 4
CStep 3
DNo error
💡 Hint
Look at the 'Result' column for step 5 in the execution_table.
If the interface Person had a key 'height', what would change in the execution_table?
AThe variable key could not be assigned "name"
BThe union type would include "height"
CThe keyof operator would produce only "height"
DNo change
💡 Hint
Refer to step 2 where keyof produces the union of keys.
Concept Snapshot
keyof operator syntax: keyof Type
Produces a union of string literal types representing keys of Type.
Used to get valid property names of an object type.
Helps ensure safe property access and type checking.
Example: type Keys = keyof Person; // "name" | "age"
Full Transcript
The keyof operator in TypeScript takes an object type and returns a union of its keys as string literal types. For example, given an interface Person with keys 'name' and 'age', applying keyof Person produces the union type "name" | "age". This union can be used as a type for variables to ensure they only hold valid keys of the object. Assigning a string not in the union, like "height", causes a type error. This helps catch mistakes early and makes code safer by restricting keys to those defined in the type.

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

  1. 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.
  2. 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.
  3. Final Answer:

    It creates a union type of all keys of an object type. -> Option C
  4. 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

  1. Step 1: Recall correct keyof syntax

    The correct syntax is keyof TypeName without parentheses or dot notation.
  2. 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.
  3. Final Answer:

    type Keys = keyof Person; -> Option D
  4. 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

  1. 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.
  2. Step 2: Check console output

    The console logs the value of key, which is 'year'. No errors occur.
  3. Final Answer:

    'year' -> Option A
  4. 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

  1. 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'.
  2. Step 2: Correct property access syntax

    To use a variable key, bracket notation obj[key] is required to access the dynamic property.
  3. Final Answer:

    Using dot notation with variable key instead of bracket notation. -> Option A
  4. 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

  1. 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.
  2. 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.
  3. 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.
  4. Final Answer:

    function getProp<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } -> Option B
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard