Concept Flow - Indexed access types
Define object type
Use indexed access type: Type[Key
Extract property type
Use extracted type in variable or function
Indexed access types let you get the type of a property from an object type using its key.
type Person = { name: string; age: number };
let personName: Person['name'];
personName = "Alice";| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Define type Person | Person = { name: string; age: number } | Person type created |
| 2 | Use indexed access type Person['name'] | Person['name'] | string |
| 3 | Declare variable personName with type Person['name'] | let personName: Person['name'] | Variable declared |
| 4 | Assign "Alice" to personName | personName = "Alice" | personName = "Alice" |
| 5 | Use personName as string | typeof personName | "string" |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| personName | undefined | undefined | undefined | undefined | "Alice" |
Indexed access types syntax: TypeName[Key] Extracts the type of a property from an object type. Useful to reuse property types without repeating. Example: type NameType = Person['name'] gives string. Keeps types consistent and DRY.