/** * A helper type to generate dot-prefixed keys. */ type DotPrefix = T extends '' ? '' : `.${T}`; /** * Recursively generates all possible dot-notation paths for a nested object type. */ type Path = (T extends object ? { [K in keyof T]: `${K}${DotPrefix>}` }[keyof T] : '' ) extends infer P ? P : never; interface UserSettings { theme: 'dark' | 'light'; language: string; notifications: { email: boolean; sms: boolean; push: { enabled: boolean; frequency: 'daily' | 'weekly'; }; }; profile: { firstName: string; lastName: string; }; preferences?: { privacy: boolean; }; } type UserSettingPaths = Path; /* type UserSettingPaths = "theme" | "language" | "notifications" | "profile" | "preferences" | "notifications.email" | "notifications.sms" | "notifications.push" | "profile.firstName" | "profile.lastName" | "preferences.privacy" | "notifications.push.enabled" | "notifications.push.frequency" */ // Example Usage: function getSetting>(obj: T, path: K): any { const parts = path.split('.'); let current: any = obj; for (const part of parts) { if (current === undefined || current === null) return undefined; current = current[part]; } return current; } const settings: UserSettings = { theme: 'dark', language: 'en', notifications: { email: true, sms: false, push: { enabled: true, frequency: 'daily' } }, profile: { firstName: 'John', lastName: 'Doe' } }; const theme = getSetting(settings, 'theme'); // string: 'dark' const emailNotifications = getSetting(settings, 'notifications.email'); // boolean: true const pushFrequency = getSetting(settings, 'notifications.push.frequency'); // 'daily' | 'weekly': 'daily' // const invalidPath = getSetting(settings, 'notifications.foo'); // Type Error! // This utility is extremely useful for form libraries, i18n key management, // and safe access to nested properties without string literals errors.