Skip to content

Instantly share code, notes, and snippets.

@revskill10
Created July 13, 2023 14:15
Show Gist options
  • Save revskill10/ff3c663709b8884d5e88b3748bf59a0f to your computer and use it in GitHub Desktop.
Save revskill10/ff3c663709b8884d5e88b3748bf59a0f to your computer and use it in GitHub Desktop.
Simple i18n helpers
type Path<T, Key extends keyof any = keyof T> = Key extends keyof T
? T[Key] extends object
? T[Key] extends infer R
? `${Key & string}.${Path<R, keyof R>}` | `${Key & string}`
: never
: `${Key & string}`
: never;
type Paths<T> = Path<T> extends string ? Path<T> : never;
function translation<T, P extends Paths<T>>(
obj: T,
path: P,
): P extends keyof T ? T[P] : never {
const keys = path.split('.') as Array<keyof T>;
let result: any = obj;
for (const key of keys) {
result = result[key];
}
return result;
}
const translations = {
path: {
to: {
key: 'a string',
},
},
};
console.log(translation(translations, 'path.to')); // { key: 'a string' }
console.log(translation(translations, 'path.too')); // Error
console.log(translation(translations, 'path.to.invalidKey')); // Error
console.log(translation(translations, 'path.to.key')); // 'a string'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment