Lesson 29 of 55
15 mins readPython Type Parameters in Generic Constraints (keyof)
In Plain English
You can declare a type parameter that is constrained by another type parameter to safely extract property values with getProperty(obj, key).
Core Rules to Remember

K extends keyof T: Constrains K to only valid property names of object type T.

Indexed Return T[K]: Automatically infers the exact property return type matching key K.
Live Interactive Example
Hit Run Code to see it liveSafe Property Access with keyof
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Output Console
Click "Run Code" to view the rendered output.
How it works: T is serverConfig shape, K is constrained to valid keys, and return type is indexed type T[K].
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Implement Safe Property Plucker
Write function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] that maps each item to item[key].
Pluck "name" from [{ name: "Alice", age: 30 }, { name: "Bob", age: 25 }] and print JSON stringified result.
1
2
3
4
5
6
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.