Typed object paths
Concept and syntax
A bounded path model can produce direct keys and one nested level using a mapped union and template strings. Restrict the domain to required plain records with string keys; arrays, optional properties and dotted names require separate policy. No path traversal is performed by the type.
Working example
Save each snippet separately as main.ts in a fresh directory with TypeScript 5.8.3. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts and run accepted snippets with node main.js. Type aliases are erased; assignments and diagnostic checks demonstrate the type relations, not the printed output alone.
type Paths<T>={[K in keyof T & string]:T[K] extends object?K|`${K}.${keyof T[K] & string}`:K}[keyof T & string]; type P=Paths<{id:number;meta:{label:string}}> ;const p:P="meta.label"; console.log(p);Expected output:
meta.labelCommon mistake
Intentionally invalid; compile separately and do not execute.
type Paths<T>={[K in keyof T & string]:T[K] extends object?K|`${K}.${keyof T[K] & string}`:K}[keyof T & string]; type P=Paths<{id:number;meta:{label:string}}> ;const p:P="meta.missing";Expected diagnostic: TS2322. missing is not a key of meta.
Practice and recap
Add a second nested field and list accepted paths.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Typed object paths — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Typed object paths is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Paths<T>={[K in keyof T & string]:T[K] extends object?K|`${K}.${keyof T[K] & string}`:K}[keyof T & string]; type P=Paths<{id:number;meta:{label:string}}> ;const p:P="meta.label"; console.log(p);Which diagnostic and explanation match the rejected example under the lesson settings?
type Paths<T>={[K in keyof T & string]:T[K] extends object?K|`${K}.${keyof T[K] & string}`:K}[keyof T & string]; type P=Paths<{id:number;meta:{label:string}}> ;const p:P="meta.missing";Which path is valid for {meta:{label:string}} under Paths?