Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Created February 28, 2025 08:07
Show Gist options
  • Save mindplay-dk/e185a388634a8b68a8708648a32748c9 to your computer and use it in GitHub Desktop.
Save mindplay-dk/e185a388634a8b68a8708648a32748c9 to your computer and use it in GitHub Desktop.
Type-safe language translations in TypeScript
// We define a default master language and primary translation
// Types are extracted from that, and other translations must
// then conform to the primary translation.
const DANISH = {
"Hello {name}!": "Hej {name}",
"Welcome to the world": "Velkommen til Verden",
}
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",
} satisfies Language // 👈 type checking ✨
const translator = (lang: Language) =>
(key: TranslationKey, values: Record<string, string> = {}) =>
(lang[key] || key).replace(/{([^{}]+)}/g, (match, key) => key in values ? values[key] : match)
// EXAMPLES:
let t = translator(DANISH)
console.log(t("Hello {name}!", { name: "Joe" }))
console.log(t("Welcome to the world"))
t = translator(ENGLISH)
console.log(t("Hello {name}!", { name: "Joe" }))
console.log(t("Welcome to the world"))
t = translator(GERMAN)
console.log(t("Hello {name}!", { name: "Joe" }))
console.log(t("Welcome to the world"))
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