Created
April 9, 2023 10:48
-
-
Save bhumit070/8e9b799e5c387afded8013dd0a187216 to your computer and use it in GitHub Desktop.
nested object keys type
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
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'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
taken from this Youtube Video by Tech Talks with Simon