Created
June 1, 2023 17:26
-
-
Save mikimaine/623eaab3107225c01925f7d40a7b6745 to your computer and use it in GitHub Desktop.
A TypeScript type that will dynamically knows every nested object property. specially helpful when being used on a dynamic size object you want to access.
This file contains 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 ShapeOf<T extends Record<string, any>> = keyof { | |
[K in keyof T as T[K] extends string ? K: T[K] extends Record<string, unknown> ? `${K & string}.${ShapeOf<T[K]> & string}` : never]: any | |
} | |
const locales = { | |
en: { | |
welcome: 'welcome', | |
job: { | |
title: 'Job title', | |
description: 'Job description' | |
}, | |
footer: { | |
left: 'sample footer left', | |
right: { | |
top: 'sample footer right' | |
} | |
} | |
} | |
} | |
type LocaleMap = typeof locales | |
type LocaleName = keyof LocaleMap | |
type Locale = LocaleMap[LocaleName] | |
let currentLocale: LocaleName = 'en' | |
function get(object: Record<string, unknown>, path: Array<string>, index = 0): string { | |
const key = path[index] | |
if(key === undefined) { | |
return '' | |
} | |
const result = object[key] | |
if(result === undefined) { | |
return '' | |
} | |
if(typeof result === 'string') { | |
return result; | |
} | |
return get(Object(result), path, index + 1) | |
} | |
export function t(key: ShapeOf<Locale>) { | |
return get(locales[currentLocale], key.split('.')) | |
} | |
t("footer.right.top") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment