Skip to content

Instantly share code, notes, and snippets.

@pfftdammitchris
Created July 18, 2026 06:06
Show Gist options
  • Select an option

  • Save pfftdammitchris/510521436e885928f001292f572151c5 to your computer and use it in GitHub Desktop.

Select an option

Save pfftdammitchris/510521436e885928f001292f572151c5 to your computer and use it in GitHub Desktop.
TypeScript Generic Constraints in Depth: `extends`, `keyof`, and the Patterns That Prevent Runtime Errors - snippet-4.ts
type PathsToStringProps<T> = {
[K in keyof T]: T[K] extends string
? K
: T[K] extends object
? `${K & string}.${PathsToStringProps<T[K]> & string}`
: never;
}[keyof T];
function getNestedString<T, P extends PathsToStringProps<T>>(
obj: T,
path: P
): string {
const keys = (path as string).split(".");
let value: any = obj;
for (const key of keys) {
value = value[key];
}
return value;
}
const data = {
user: {
profile: {
email: "alice@example.com",
age: 30,
},
},
};
// Valid: path resolves to string property
const email = getNestedString(data, "user.profile.email");
// Compiler error: path does not resolve to string property
const age = getNestedString(data, "user.profile.age");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment