Created
July 18, 2026 06:06
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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