Last active
May 13, 2025 06:50
-
-
Save mindplay-dk/e185a388634a8b68a8708648a32748c9 to your computer and use it in GitHub Desktop.
Type-safe language translations in TypeScript
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
const DANISH = { | |
"Hello {{name}}!": "Hej {{name}}", | |
"Welcome to the world": "Velkommen til Verden", | |
"You have {{amount}} {{cookies}}": "Du har {{amount}} {{cookies}}", | |
"cookie": "kage", | |
"cookies": "kager", | |
"Missing translation": "Manglende oversættelse", | |
} | |
type TranslationKey = keyof typeof DANISH | |
type Language = Record<TranslationKey, string> | |
const ENGLISH = {} as Language | |
const GERMAN = { | |
"Hello {{name}}!": "Hallo {{name}}", | |
"Welcome to the world": "Willkommen in Der Welt", | |
"You have {{amount}} {{cookies}}": "Du hast {{amount}} {{cookies}}", | |
"cookie": "kuche", | |
"cookies": "kuchen" | |
} satisfies Language // 👈 type checking ✨ | |
const translator = (lang: Language) => | |
(key: TranslationKey, values: Record<string, string|{ toString(): string }> = {}) => | |
(lang[key] || key).replace(/{{([^{}}]+)}}/g, (match, key) => String(key in values ? values[key] : match)) | |
// EXAMPLES: | |
let numCookies = 1 | |
for (const language of [DANISH,ENGLISH,GERMAN]) { | |
const t = translator(language) | |
console.log(t("Hello {{name}}!", { name: "Joe" })) | |
console.log(t("Welcome to the world")) | |
console.log(t("You have {{amount}} {{cookies}}", { amount: numCookies, cookies: numCookies === 1 ? t("cookie") : t("cookies") })) | |
numCookies += 1 | |
} | |
const t = translator(DANISH) | |
console.log(t("This message is undefined")) // 👈 type checking ✨ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment