`T[K]` — Reach Into a Type
Lookup Types
Indexed access lets you grab the type of a property by key, index into tuples, and extract value types from unions of keys.
What you'll learn
- Look up a property type with `T[K]`
- Index into tuples and arrays
- Use unions of keys to build sub-types
We touched indexed access in the earlier lesson on T[K]. Now
that we have keyof, mapped types, and conditional types, here
are the patterns you’ll use most.
Pull a Property’s Type
type User = { id: string; age: number; admin: boolean };
type Age = User["age"]; // number
type Id = User["id"]; // string The type-level version of user.age.
Many Keys at Once
type Values = User[keyof User]; // string | number | boolean
type AB = User["id" | "age"]; // string | number A union of keys gives you a union of value types.
Array Element Types
const colors = ["red", "green", "blue"] as const;
type Color = typeof colors[number]; // "red" | "green" | "blue" array[number] is the element type. Common pattern: define a
constant tuple of strings, derive the union from it. One source
of truth — runtime and type.
Tuple Indexing
type Pair = [string, number];
type First = Pair[0]; // string
type Second = Pair[1]; // number Tuples are indexable by numeric literal.
A Real Pattern: Action Types
const actions = {
increment: (by: number) => ({ type: "INCREMENT", by }),
reset: () => ({ type: "RESET" }),
} as const;
type ActionMap = {
[K in keyof typeof actions]: ReturnType<typeof actions[K]>
};
type Action = ActionMap[keyof ActionMap];
// { type: "INCREMENT"; by: number } | { type: "RESET" } Define the action creators once. Derive the action union from their return types. Zero duplicate typing.
Caveats
- You can only index with types that are valid keys of
T.User["nope"]errors. - Indexing an array with a numeric literal gives that element’s type — but indexing with
numbergives the union of all element types.
End of Chapter
That wraps the advanced type tools. Next chapter: how TypeScript extends classes — access modifiers, abstract classes, decorators, enums, the works.
Classes in TS →