If you're looking to achieve this, consider utilizing a recursive conditional type that navigates through the path tuple:
type KeyPath = readonly PropertyKey[]
type SOMETHING<P extends KeyPath, T> =
P extends readonly [infer Key, ...infer Rest]
? {[K in Extract<Key, PropertyKey>]: SOMETHING<Extract<Rest, KeyPath>,T>}
: T
type Path = readonly ['a', 'b'];
type Obj = SOMETHING<Path, {c: "foo"}>; // {a: {b: {c: "foo" } } }
The utilization of Extract
is crucial as it ensures the inferred arguments meet the necessary constraints. The inclusion of Extract<Rest, KeyPath>
could be omitted if the extends KeyPath
was excluded from SOMETHING
, but this would eliminate the tuple check on the path argument.
Take a look at TypeScript playground for more details