TS Indexed Access
Indexed access types look like property lookups but operate at the type level. They let you ask: "what's the type of this key?"
Basic shape
TS
type User = { id: number; name: string; tags: string[] };
type Id = User['id']; // number
type Name = User['name']; // string
type Tags = User['tags']; // string[]
Union of keys
TS
type IdOrName = User['id' | 'name']; // number | string
keyof + indexed access = all values
TS
type AllValues = User[keyof User]; // number | string | string[]
Array element type
TS
type StringArray = string[];
type Element = StringArray[number]; // string
const users = [{ id: 1 }, { id: 2 }];
type U = typeof users[number]; // { id: number }
Tuple element types
TS
type Pair = [string, number]; type First = Pair[0]; // string type Second = Pair[1]; // number type Any = Pair[number]; // string | number
Indexed access into a Record
TS
type CssVars = Record<'primary' | 'secondary', string>; type CssVar = CssVars[keyof CssVars]; // string
Practical example — react event handlers
TS
type ButtonProps = JSX.IntrinsicElements['button']; type ClickHandler = ButtonProps['onClick'];
Tip: Combine with
typeof and as const to derive types from runtime data. typeof users[number] says "an element of the users array" — no need to write the User type twice.Example
Example
type User = { id: number; name: string; tags: string[] };
type Tag = User['tags'][number]; // string
const t: Tag = 'admin';
console.log(t);
Try it Yourself »
Exercise
Get the element type of "users: User[]".
type U = (typeof users)[
];
Six letters.
Discussion
Loading…