Typed Locale

Locale and Type Declaration

Estimated reading time: 2 minutes

When using typed-locale, it's important to properly define your translation objects and their corresponding types. This ensures type safety throughout your application and provides excellent autocompletion in your IDE.

Creating Translation Objects

First, let's create a translation object for the default language (usually English):

import {plural} from 'typed-locale'; export const en = { hello: 'Hello', helloName: 'Hello, {{name}}', youHaveMessages: plural({ none: 'You have no messages', one: 'You have 1 message', other: 'You have {{count}} messages', }), } as const;

Note the use of as const at the end of the object. This is crucial for TypeScript to infer the most specific types possible.

Defining Types

After creating your translation object, you should define its type using the InferTranslation utility type provided by typed-locale:

import {InferTranslation} from 'typed-locale'; type Translation = InferTranslation<typeof en>;

This Translation type will now represent the structure of your translations, including all nested objects and pluralization rules.

Creating Other Language Objects

For other languages, you can create objects that conform to the Translation type:

export const fr: Translation = { hello: 'Bonjour', helloName: 'Bonjour, {{name}}', youHaveMessages: plural({ none: 'Vous n'avez aucun message', one: 'Vous avez 1 message', other: 'Vous avez {{count}} messages', }), };

If you're working on a new language and don't have all translations ready yet, you can use InferPartialTranslation:

import {InferPartialTranslation} from 'typed-locale'; export const de: InferPartialTranslation<Translation> = { hello: 'Hallo', helloName: 'Hallo, {{name}}', // youHaveMessages can be added later };

This allows you to gradually add translations without TypeScript complaining about missing keys.

Creating a Dictionary

Once you have your translation objects, you can create a dictionary:

const dictionary = {en, fr, de};

This dictionary can then be used to create a translator, as shown in the "Create Translator" section of the documentation.

By following these steps, you ensure that your translations are type-safe and that you'll get proper IDE support when using them throughout your application.