Created
February 28, 2025 08:07
-
-
Save mindplay-dk/e185a388634a8b68a8708648a32748c9 to your computer and use it in GitHub Desktop.
Type-safe language translations in TypeScript
This file contains 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
// 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