BeginnerCoder

Lesson 19 — keyof & indexed access

Types from an object's keys

keyof T is the union of an object type's property names: for { name: string; age: number } it is "name" | "age". T[K] is an indexed access type — the type of property K. Together they let a function accept only real keys and return the correct type for each one.

type User = { name: string; age: number };
type Keys = keyof User;      // "name" | "age"
type Age = User["age"];      // number

Why it matters: generic getters, form helpers and sort-by-field functions all use this to stay safe.

Want it another way?
Task

Make get generic with K extends keyof T, return o[k], and print Sam then 30.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with TypeScript Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.