Lesson 37 of 55
15 mins readPython The keyof Type Operator
In Plain English
The keyof operator takes an object type and produces a string or numeric literal union of its keys, allowing dynamic metaprogramming.
Core Rules to Remember

Literal Union of Keys: Produces a union of all property names of a type.

Metaprogramming Foundation: Forms the building block for mapped and indexed access types.
Live Interactive Example
Hit Run Code to see it liveExtracting Keys from Types
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Output Console
Click "Run Code" to view the rendered output.
How it works: keyof SystemConfig generates the literal union "host" | "port" | "timeout" | "sslEnabled".
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Enforce Allowed Metrics Keys
Define interface NodeMetrics { cpu: number; memory: number; disk: number }.
Create type MetricName = keyof NodeMetrics.
Write function trackMetric(metric: MetricName, val: number): void logging `${metric}: ${val}`.
Call trackMetric("cpu", 85).
1
2
3
4
5
6
7
8
9
10
11
12
13
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.