i18n
Nested translation keys with typed placeholders
Load locale dictionaries, switch language, and interpolate parameters. Nested keys use dots. Missing keys fall back to the default locale, then to the key string itself.
Import
import { I18n } from "semola/i18n";Quick start
The instance starts in English, switches to Spanish, then translates a plain key and an interpolated message.
const i18n = new I18n({
defaultLocale: "en",
locales: {
en: {
greeting: "Hello",
welcome: "Welcome, {name:string}!",
messages: {
unread: "You have {count:number} unread messages",
},
},
es: {
greeting: "Hola",
welcome: "Bienvenido, {name:string}!",
},
},
});
i18n.setLocale("es");
i18n.translate("greeting"); // "Hola"
i18n.translate("welcome", { name: "Ada" }); // "Bienvenido, Ada!"Placeholders
In message strings, declare the type next to the name:
{name:string} {count:number} {active:boolean}The type annotation is for TypeScript / documentation; at runtime values are stringified. Pass matching values as the second argument to translate.
Locale control
setLocale() changes the active dictionary, and getLocale() returns its locale key.
i18n.setLocale("en");
i18n.getLocale(); // "en"The instance starts on defaultLocale. Nested keys: "messages.unread".
Examples
Translate a nested key
translate() follows the dot path and replaces the typed number placeholder.
i18n.translate("messages.unread", { count: 3 });
// "You have 3 unread messages"Fall back to the default locale
Because Spanish has no messages.unread, lookup falls back to the English dictionary.
i18n.setLocale("es");
// "messages.unread" missing in es → falls back to en
i18n.translate("messages.unread", { count: 1 });Switch language at runtime
Changing the active locale makes the same function return a different translation without rebuilding the instance.
function greet(name: string) {
return i18n.translate("welcome", { name });
}
i18n.setLocale("en");
greet("Ada"); // "Welcome, Ada!"
i18n.setLocale("es");
greet("Ada"); // "Bienvenido, Ada!"Reference
Constructor
| Option | Meaning |
|---|---|
defaultLocale | Locale used at start and for fallback |
locales | Map of locale → nested message dictionaries |
Methods
| Method | Meaning |
|---|---|
setLocale(locale) | Switch active locale |
getLocale() | Current locale |
translate(key, params?) | Resolve a key (dot path) with optional params |