Created
July 13, 2023 14:15
-
-
Save revskill10/ff3c663709b8884d5e88b3748bf59a0f to your computer and use it in GitHub Desktop.
Simple i18n helpers
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
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