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.
Person['name'] represent?Type['property'] extracts the type of the specified property from the given type.Person['name'] is the type of the 'name' property inside the Person type.age from type Person using indexed access types?Type['property'].Person['age']. Others use dot notation or parentheses which are invalid here.type Person = { name: string; age: number; }, what is the type of Person['age']?Person['age'] is the type number.type Person = { name: string; age: number; };
type AgeType = Person[age];Person[age], 'age' should be a string literal in quotes: Person['age'].age as a variable, which is undefined here, causing an error.type Config = { options: { debug: boolean; verbose: boolean; }; version: string; }, which type correctly extracts the type of the debug property using indexed access types?Config['options']['debug'] to get the type of 'debug'.Pass the test and this pattern moves unknown