Sub topic 1
Reading keys and property types with keyof and T[K]
This chapter covers two type operators that every mapped and conditional type relies on: keyof, which produces the union of an object type's property names, and indexed access, written T[K], which looks up the type of one property.
Prerequisites
This chapter assumes you know object types, union types, and generics with extends constraints. You should also be comfortable with type aliases. You do not need mapped types yet, since the next chapter builds on this one.
Getting property names with keyof
keyof T takes an object type T and returns a union of its property names as literal types.
type User = { id: number; name: string; email?: string };
type UserKeys = keyof User;
// "id" | "name" | "email"Optional properties still appear in keyof. The ? affects only whether a property may be missing, not whether its name exists.
Getting property types with T[K]
Indexed access T[K] returns the type stored at key K in T. The key must be a member of keyof T.
type IdType = User["id"]; // number
type NameType = User["name"]; // string
type ValueTypes = User[keyof User];
// number | string | undefinedThe last line indexes with a union of keys, so TypeScript returns the union of each property's type. The undefined comes from the optional email property under strictNullChecks.
Writing a generic helper
Combine the two operators with a type parameter constrained by keyof. This keeps the key and the return type in sync.
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user: User = { id: 1, name: "Ada" };
const name = getProp(user, "name"); // string
const id = getProp(user, "id"); // number
// getProp(user, "age");
// Error: Argument of type '"age"' is not assignable to parameter of type 'keyof User'.TypeScript infers K from the literal string you pass, then uses T[K] as the return type. A typo in the key fails at compile time instead of returning undefined at runtime.
Common errors
- Widened keys. If
Thas a string index signature such as{ [key: string]: number }, thenkeyof Tbecomesstring | number. Lookups then accept any string. - Missing constraint. Writing
function f<T, K>(obj: T, key: K): T[K]fails becauseKmay not be a key ofT. AddK extends keyof T. - Expecting runtime checks. Both operators exist only at compile time. They produce no JavaScript.
Exercise
Given type Product = { sku: string; price: number; tags?: string[] }, what is the type of Product[keyof Product]?
Show answer
string | number | string[] | undefined. The union includes each property's type, and the optional tags adds undefined.
Mapped types, covered next, use keyof in the same way to rewrite every property at once.