Skip to content

Instantly share code, notes, and snippets.

@mikimaine
Created June 1, 2023 17:26
Show Gist options
  • Save mikimaine/623eaab3107225c01925f7d40a7b6745 to your computer and use it in GitHub Desktop.
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.
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