← All Exercises
Type-Safe Dot-Path Getter
advancedtypescript
Background
Typed path getters appear in form libraries, i18n helpers, and state selectors. Template-literal types can compute the value type, but the runtime still has to walk untrusted objects safely.
Problem
Implement getPath<T, P extends string>(source, path) where P is a dotted path such as user.profile.city or user.roles.1. The return type must resolve to the nested value type through template-literal inference, arrays must be indexed by numeric path segments, and missing paths must return undefined at runtime.
Input
A JSON object with doc (a user document) and keys, where each key maps to a known dotted path.
Output
A JSON object with values, where each entry is the resolved value or null when the path is missing.
Sample tests
Sample 1
Input: {"doc":{"user":{"name":"Ada","roles":["admin","dev"],"profile":{"city":"Paris"}}},"keys":["name","role","city","profile","missing"]}Expected: {"values":["Ada","dev","Paris",{"city":"Paris"},null]}Sample 2
Input: {"doc":{"user":{"name":"Ada","roles":[],"profile":{"city":"Paris"}}},"keys":["role","absent"]}Expected: {"values":[null,null]}Your solution
Learning objective
Practice recursive conditional types, template-literal inference, and runtime traversal that agrees with the compile-time path type.