Typed Locale

Create Translator

Estimated reading time: 2 minutes

There are two main ways to create a translator in typed-locale:

  1. Using createTranslator for a single language
  2. Using createTranslatorFromDictionary for multiple languages

Using createTranslator

For single-language applications or when you want to create a translator for a specific language, use the createTranslator function:

import {createTranslator} from 'typed-locale'; import {en} from './translations'; const translator = createTranslator(en);

You can also provide default variables when values come from application context:

const translator = createTranslator(en, { defaultVariables: { appName: 'Acme App', }, });

Using the Translator

Once you have created a translator, you can use it to access your translations:

// Simple translation const greeting = translator(t => t.hello); console.log(greeting); // Output: 'Hello' // Translation with variables const nameGreeting = translator(t => t.helloName({name: 'World'})); console.log(nameGreeting); // Output: 'Hello, World' // Translation with default variables const welcome = translator(t => t.welcome); console.log(welcome); // Output: 'Welcome to Acme App' // Phrase variables override default variables const customWelcome = translator(t => t.welcome({appName: 'Custom App'})); console.log(customWelcome); // Output: 'Welcome to Custom App' // Nested translations const nestedGreeting = translator(t => t.nested.greeting); console.log(nestedGreeting); // Output: 'Nested greeting'

The translator function takes a callback that receives the translation object and returns the desired translation key. This approach provides excellent type safety and autocompletion in your IDE.

Type Safety

One of the key benefits of using typed-locale's translator is the type safety it provides:

  1. It ensures that you only access valid translation keys.
  2. It enforces the correct usage of variables in translations.
  3. It provides autocompletion for translation keys in your IDE.

For example, trying to access a non-existent key or providing incorrect variables will result in TypeScript errors.