Skip to content

Instantly share code, notes, and snippets.

@natanfeitosa
Last active September 3, 2025 00:09
Show Gist options
  • Save natanfeitosa/e903f2e55df99606c1028c7690945ec3 to your computer and use it in GitHub Desktop.
Save natanfeitosa/e903f2e55df99606c1028c7690945ec3 to your computer and use it in GitHub Desktop.
type GetArrayIndexValue<A extends [], K extends number | string> = K extends `.${infer I}` ? GetArrayIndexValue<A, I> : K extends number ? A[K] : never
type GetObjectPathValue<O extends object, P extends string> = P extends `${infer A}.${infer B}` ? A extends keyof O ? O[A] extends object ? GetObjectPathValue<O[A], B> : O[A] : never : P extends keyof O ? O[P] extends [] ? GetArrayIndexValue<O[P], P> : O[P] : never
const obj = {
a: {
b: 1,
c: [1, 2],
d: [
[12],
{
e: 1,
f: [
'f'
]
}
]
}
} as const
type objType = typeof obj
/*{
readonly b: 1;
readonly c: readonly [1, 2];
readonly d: readonly [readonly [12], {
readonly e: 1;
readonly f: readonly ["f"];
}];
}*/
type a = GetObjectPathValue<objType, 'a'>
// 1
type b = GetObjectPathValue<objType, 'a.b'>
// readonly [1, 2]
type c = GetObjectPathValue<objType, 'a.c'>
// 1
type c0 = GetObjectPathValue<objType, 'a.c.0'>
// readonly [12]
type d0 = GetObjectPathValue<objType, 'a.d.0'>
// 12
type d00 = GetObjectPathValue<objType, 'a.d.0.0'>
// { readonly e: 1; readonly f: readonly ["f"]; }
type d1 = GetObjectPathValue<objType, 'a.d.1'>
// 1
type d1e = GetObjectPathValue<objType, 'a.d.1.e'>
// readonly ["f"]
type d1f = GetObjectPathValue<objType, 'a.d.1.f'>
// "f"
type d1f0 = GetObjectPathValue<objType, 'a.d.1.f.0'>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment