Last active
July 26, 2025 08:14
-
-
Save zayniddindev/3639d87e2edfb84c90f25cdd3de55b98 to your computer and use it in GitHub Desktop.
Mapper for language-specific content to a specific language
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
| enum Language { | |
| UZ = 'UZ', | |
| EN = 'EN', | |
| RU = 'RU', | |
| } | |
| interface IContent { | |
| uz: string; | |
| ru: string; | |
| en: string; | |
| } | |
| type NestedContent<T> = { | |
| [K in keyof T]: T[K] extends IContent | |
| ? string | |
| : T[K] extends Array<infer U> | |
| ? U extends IContent | |
| ? string[] | |
| : NestedContent<U>[] | |
| : T[K] extends object | |
| ? NestedContent<T[K]> | |
| : T[K]; | |
| }; | |
| export function mapLanguage<T>( | |
| data: T, | |
| lang: Language, | |
| ): T extends IContent ? string : T extends Array<infer U> ? (U extends IContent ? string[] : NestedContent<U>[]) : NestedContent<T> { | |
| // Handle arrays | |
| if (Array.isArray(data)) { | |
| return (data as unknown[]).map((item) => mapLanguage(item as IContent, lang)) as unknown as ReturnType<typeof mapLanguage<T>>; | |
| } | |
| // Handle IContent objects | |
| if (data && typeof data === 'object' && 'uz' in data && 'ru' in data && 'en' in data) { | |
| return (data as IContent)[lang.toLocaleLowerCase()] as unknown as ReturnType<typeof mapLanguage<T>>; | |
| } | |
| // Handle plain objects | |
| if (data && typeof data === 'object') { | |
| const result = {} as Record<string, unknown>; | |
| for (const key in data) { | |
| const value = data[key as keyof typeof data]; | |
| if (value !== null && typeof value === 'object') { | |
| result[key] = mapLanguage(value, lang); | |
| } else { | |
| result[key] = value; | |
| } | |
| } | |
| return result as unknown as ReturnType<typeof mapLanguage<T>>; | |
| } | |
| // Fallback for primitives | |
| return data as unknown as ReturnType<typeof mapLanguage<T>>; | |
| } | |
| // Example usage | |
| const data = [{ key: { value: { uz: 'Dasturlash', ru: 'Программирование', en: 'Programming' } } }]; | |
| const mappedData = mapLanguage(data, Language.RU); | |
| console.log(mappedData); // { key: { value: 'Программирование' } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment