How can I develop a generic type that resolves to the data type of a nested property?
Assume I have a configuration structure
type Config = {
parent: {
child: boolean
}
}
I am looking for something like
type ChildConfigType = NestedDataType<Config, 'parent.child'> // boolean
type ParentConfigType = NestedDataType<Config, 'parent'> // {child: boolean}
I already have a simple implementation for non-nested types
function getProperty<
Type extends object,
Key extends keyof Type
>(key: Key): Type[Key] {
return {} as Type[Key]
}
getProperty<Config>('parent')
Furthermore, I have utility types for non-nested properties that are functional
type PropertiesOf<
Type extends object
> = keyof Type
type TypeOfProperty<
Type extends object,
Key extends PropertiesOf<Type>
> = Type[Key]
function getPropertyWithUtility<
Type extends object,
Key extends PropertiesOf<Type>
>(key: Key): TypeOfProperty<Type, Key> {
return {} as TypeOfProperty<Type, Key>
}
There is also a helper called NestedPropertiesOf that generates a union of nested properties
type NestedPropertiesOf<Type extends object> =
{
[key in keyof Type & (string | number)]: Type[key] extends object
? `${key}` | `${key}.${NestedPropertiesOf<Type[key]>}`
: `${key}`
}[keyof Type & (string | number)]
type NestedConfigProperties = NestedPropertiesOf<Config> // 'parent' | 'parent.child'
My goal is to implement a function with the following signature
function getNestedProperty<
Type extends object,
Key extends NestedPropertiesOf<Type>
>(key: Key): NestedTypeOfProperty<Type, Key> {
return {} as NestedTypeOfProperty<Type, Key>
}
getNestedProperty<Config>('parent.child')
I'm beginning to think this might not be feasible because TypeScript types cannot directly manipulate strings, making it impossible to remove the first segment of the path.