#typescript
#types
#advanced
Day 19: The keyof Operator
Extracting Keys
Welcome to Phase 4: Advanced Type Manipulation. We rely less on “writing” types and more on “calculating” them. First up: keyof.
What is keyof?
The keyof operator takes an object type and returns a union of its keys.
type Point = { x: number; y: number };
type P = keyof Point; // "x" | "y"
Indexed Access Types
We can access the type of a property using square brackets, just like in JavaScript.
type Person = { age: number; name: string; alive: boolean };
type Age = Person["age"]; // number
type I1 = Person["age" | "name"]; // number | string
type I2 = Person[keyof Person]; // number | string | boolean
Real-world Example
Building a dynamic getProperty function (revisiting Day 16).
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
Now T[K] ensures the return type matches the actual property type!
const user = { id: 1, name: "Jack" };
const userName = getProp(user, "name"); // Type is string
Challenge for Today
- Create an interface
APIResponsewithdata,status,error. - Use
keyofto create a typeResponseKeys. - Use Indexed Access to get the type of
data.
See you on Day 20 for Utility Types!