Indexed access types
Concept and syntax
T[K] looks up the type of a property using a type-level key. A union of keys produces a union of the corresponding property types. ArrayType[number] extracts an element type. These expressions do not access a runtime object; keys must be valid for the indexed type.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
type Item={id:number;label:string};const id:Item["id"]=7;const tag:string[][number]="tea";console.log(id,tag);Expected output:
7 teaCommon mistake
Intentionally invalid; compile separately and do not execute.
type Item={id:number;label:string};type Missing=Item["missing"];Expected diagnostic: TS2339. Item has no missing property. Index with a known key.
Practice and recap
Extract the union of id and label property types using two keys.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Indexed access types — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Item={id:number;label:string};const id:Item["id"]=7;const tag:string[][number]="tea";console.log(id,tag);Which diagnostic and explanation match the rejected example under the lesson settings?
type Item={id:number;label:string};type Missing=Item["missing"];