i18n Message Catalog With satisfies
Type message catalogs with a mapped Renderer so each key accepts exactly its own argument tuple, while satisfies checks every locale without widening keys.
Code
// Each message key fixes its own parameter list; every locale must satisfy it.
type Messages = {
welcome: (name: string) => string;
cartCount: (count: number) => string;
};
// Mapped over Messages so each entry accepts exactly its own argument tuple
type Renderer = { [K in keyof Messages]: (...args: Parameters<Messages[K]>) => string };
type Locale = 'en' | 'zh-cn';
const en: Renderer = {
welcome: (name) => `Welcome back, ${name}!`,
cartCount: (count) => `${count} item(s) in your cart`,
};
const zh: Renderer = {
welcome: (name) => `欢迎回来,${name}!`,
cartCount: (count) => `购物车里有 ${count} 件商品`,
};
// satisfies validates every locale against Renderer without widening keys
const i18n = {
en,
'zh-cn': zh,
} satisfies Record<Locale, Renderer>;
// Parameters<Messages[K]> plus the mapped Renderer keeps key and args
// correlated: wrong argument types fail to compile, not at request time.
function translate<K extends keyof Messages>(
locale: Locale,
key: K,
...args: Parameters<Messages[K]>
): string {
return i18n[locale][key](...args);
}
console.log(translate('zh-cn', 'welcome', 'Ada'));
console.log(translate('en', 'cartCount', 3));Output
Captured from a sandboxed run of this snippet in the build pipeline.
欢迎回来,Ada!
3 item(s) in your cartInside the snippet
i18n Message Catalog With satisfies is built around the function translate.
Points of care
- The toolchain already provides everything it needs in order to run.
Key statements
type Renderer = { [K in keyof Messages]: (...args: Parameters<Messages[K]>) => string };
cartCount: (count: number) => string;
welcome: (name: string) => string;
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. The file defines `translate` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.