translate
API reference for the GT translate method
Overview
The translate method is the primary translation function in the GT library.
It translates content from the source locale to a specified target locale using AI‑powered translation services.
const gt = new GT({
apiKey: 'your-api-key',
projectId: 'your-project-id'
});
const result = await gt.translate('Hello, world!', 'es');
console.log(result); // "¡Hola, mundo!"The method supports multiple content types, including plain text, ICU message format and i18next‑style messages, with optional metadata to improve translation accuracy.
Authentication required:
The translate method requires both apiKey (or devApiKey) and projectId to be configured in the GT instance.
Reference
Parameters
The translate method provides multiple overloads for different content types:
Text content
Prop
Type
JSX Content
Prop
Type
ICU Message Format
Prop
Type
i18next Format
Prop
Type
Parameter descriptions
| Parameter | Description |
|---|---|
source | The content to translate. Can be plain text, JSX elements, ICU messages, or i18next messages |
targetLocale | BCP‑47 locale code for the target language (e.g., ‘es’, ‘fr‑CA’) |
metadata | Optional translation context including context, tags, and formatting options |
Returns
Promise<TranslationResult | TranslationError>- TranslationResult: Contains the translated content and metadata
- TranslationError: Contains error information if the translation fails
Behaviour
Content Type Detection
The method automatically detects the content type based on the source parameter:
- String: Treated as plain text or ICU message format
- JSX elements: Handled as React‑style JSX content
- Objects: Processed as structured message formats
Locale Resolution
- The target locale is validated against BCP‑47 standards
- Custom locale mappings are applied if configured
- Canonical locale codes are used for API requests
Context Enhancement
When a custom mapping includes region or script codes for the target locale, they’re automatically added to the metadata to improve translation accuracy.
Examples
const gt = new GT({
apiKey: 'your-api-key',
projectId: 'your-project-id'
});
const result = await gt.translate('Welcome to our app', 'fr');
console.log(result);
// "Bienvenue dans notre application"Notes
- Translates a given string into a target locale and returns a promise
Next steps
How is this guide?