A lightweight, type-safe TypeScript module for managing multi-language translations with support for interpolation placeholders.
- Full TypeScript generic type safety — language keys and translation keys are statically inferred
- Runtime language switching via a simple setter
- String interpolation with indexed placeholders (
{0},{1}, ...) - Language change listeners with automatic unregister support
- Zero runtime dependencies
npm install @xxanderwp/translate-moduleimport { LanguageCore } from "@xxanderwp/translate-module";
const translations = {
en: {
greeting: "Hello, {0}!",
farewell: "Goodbye!",
},
es: {
greeting: "¡Hola, {0}!",
farewell: "¡Adiós!",
},
};
const lang = new LanguageCore(translations, "en");
lang.translate("greeting", "Alice"); // "Hello, Alice!"lang.currentLanguage = "es";
lang.translate("greeting", "Alice"); // "¡Hola, Alice!"lang.langKeys; // ["en", "es"]| Parameter | Type | Description |
|---|---|---|
data |
T |
An object mapping language keys to their translation dictionaries. |
defaultLanguage |
keyof T |
(Optional) The language to activate on construction. Defaults to the first key in data. |
Throws if data is empty or defaultLanguage is not a key of data.
Returns the translated string for key in the current language, with {0}, {1}, ... placeholders replaced by the provided args.
Returns the key itself as a string if the translation is missing.
Gets or sets the active language key. Setting an unsupported key throws an error.
Returns an array of all available language keys.
Returns the full translations object passed to the constructor.
Returns the translation dictionary for the currently active language.
Registers a callback to be invoked whenever the active language changes. Returns an unregister function — call it to remove the listener.
const unregister = lang.onChangeLanguage(() => {
console.log("Language changed to:", lang.currentLanguage);
});
// Later, to stop listening:
unregister();Build
npm run buildRun tests
npm testRun tests with coverage
npm run test:coverage