GT Class

GT Constructor

API reference for the GT class constructor

Overview

The GT constructor creates a new instance of the General Translation class, providing access to all translation, formatting, and locale functionality.

import { GT } from 'generaltranslation';

const gt = new GT({
  apiKey: 'your-api-key',
  projectId: 'your-project-id',
  sourceLocale: 'en',
  targetLocale: 'es'
});

The constructor will automatically check the environment for the GT_API_KEY and GT_PROJECT_ID environment variables, so you can omit them from the constructor parameters. It will also validate all provided locale codes.


Reference

Parameters

Prop

Type

The GTConstructorParams object supports the following properties:

PropertyTypeOptionalDescription
apiKeystringProduction API key for the translation service
devApiKeystringDevelopment API key (takes precedence in development)
projectIdstringUnique project identifier
sourceLocalestringDefault source locale for translations
targetLocalestringDefault target locale for translations
localesstring[]List of supported locale codes
baseUrlstringCustom API base URL (for enterprise deployments)
customMappingCustomMappingCustom locale code mappings and definitions

Returns

A new GT class instance with all translation and locale methods available.


Examples

Basic usage

import { GT } from 'generaltranslation';

// Minimal setup - uses environment variables
const gt = new GT();

With API Credentials

const gt = new GT({
  projectId: 'my-project-id',
  apiKey: 'my-api-key',
  targetLocale: 'fr'
});

With Custom Locale Mapping

You can provide a custom mapping. This allows you to (1) use aliases for locale codes, (2) override standard BCP 47 validation, and (3) override standard BCP 47 locale metadata.

For example, if you want to use cn as an alias for zh. Since the General Translation API does not support cn, you must specify a custom mapping.

const gt = new GT({
  projectId: 'my-project-id',
  apiKey: 'my-api-key',
  targetLocale: 'es',
  customMapping: {
    'cn': { code: 'zh' }
  }
});

You can do other things with custom mappings, such as adding custom names, emojis, and more.

const gt = new GT({
  projectId: 'my-project-id',
  apiKey: 'my-api-key',
  targetLocale: 'es',
  customMapping: { 'en-US': { name: 'Mandarin', emoji: '🇫🇷' } }
});

Notes

  • All parameters are optional, but API operations will require apiKey and projectId
  • The constructor validates all locale codes immediately and throws errors for invalid codes
  • Custom mappings take precedence over standard BCP 47 validation

Next steps

How is this guide?

GT Constructor