Skip to content

Instantly share code, notes, and snippets.

@bhumit070
Created April 9, 2023 10:48
Show Gist options
  • Save bhumit070/8e9b799e5c387afded8013dd0a187216 to your computer and use it in GitHub Desktop.
Save bhumit070/8e9b799e5c387afded8013dd0a187216 to your computer and use it in GitHub Desktop.
nested object keys type
const locale = {
'en_us': {
hello: 'hello',
greetings: {
morning: 'Good Morning',
evening: 'Good Evening',
else: {
foo: 'bar'
}
},
},
} as const;
type LocaleMap = typeof locale;
type LocaleKeys = keyof LocaleMap;
const current_locale: LocaleKeys = 'en_us';
type LocaleType = LocaleMap[LocaleKeys];
type Values = string | number | boolean | null | undefined;
type PathInto<T extends Record<string, any>> = keyof {
[K in keyof T as T[K] extends string
? K
: T[K] extends Record<string, any>
? `${K & string}.${PathInto<T[K]> & string}`
: never]: never;
};
function t<T>(key: PathInto<LocaleType>): string {
return locale[current_locale][key];
}
t('hello');
@bhumit070
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment