# generaltranslation: General Translation Core SDK: GT 构造函数 URL: https://generaltranslation.com/zh/docs/core/class/constructor.mdx --- title: GT 构造函数 description: GT 类构造函数的 API 参考文档 --- ## 概述 `GT` 构造函数会创建一个新的 General Translation 类实例,用于访问所有翻译、格式化和区域设置功能。 ```typescript import { GT } from 'generaltranslation'; const gt = new GT({ apiKey: 'your-api-key', projectId: 'your-project-id', sourceLocale: 'en', targetLocale: 'es' }); ``` 构造函数会自动检查环境中的 `GT_API_KEY`、`GT_DEV_API_KEY` 和 `GT_PROJECT_ID` 环境变量,因此你可以在构造函数参数中省略它们。 此外,它还会校验所有提供的区域设置代码。 *** ## 参考 ### 参数 `GTConstructorParams` 对象支持以下属性: | 属性 | 类型 | 可选 | 描述 | | --------------- | --------------- | -- | ------------------------- | | `apiKey` | `string` | ✓ | 翻译服务的生产环境 API 密钥 | | `devApiKey` | `string` | ✓ | 开发环境 API 密钥 (在开发环境中优先使用) | | `projectId` | `string` | ✓ | 项目的唯一标识符 | | `sourceLocale` | `string` | ✓ | 翻译的默认源区域设置 | | `targetLocale` | `string` | ✓ | 翻译的默认目标区域设置 | | `locales` | `string[]` | ✓ | 支持的区域设置代码数组 | | `baseUrl` | `string` | ✓ | 自定义 API 基础 URL (适用于企业部署) | | `customMapping` | `CustomMapping` | ✓ | 自定义区域设置代码映射和定义 | ### 返回值 一个新的 `GT` 类实例,可使用所有翻译和区域设置相关方法。 *** ## 示例 ### 基本用法 ```typescript import { GT } from 'generaltranslation'; // 最简配置 - 使用环境变量 const gt = new GT(); ``` ### 使用 API 凭证 ```typescript const gt = new GT({ projectId: 'my-project-id', apiKey: 'my-api-key', targetLocale: 'fr' }); ``` ### 使用自定义区域设置映射 你可以提供自定义映射。 这样,用户就可以 (1) 为区域设置代码使用别名,(2) 覆盖标准的 BCP 47 验证,以及 (3) 覆盖标准的 BCP 47 区域设置信息。 例如,假设你想用 `cn` 作为 `zh` 的别名。 由于 General Translation API 不支持 `cn`,你必须指定自定义映射。 ```typescript const gt = new GT({ projectId: 'my-project-id', apiKey: 'my-api-key', targetLocale: 'es', customMapping: { 'cn': { code: 'zh' } } }); ``` 你还可以通过自定义映射实现其他效果,例如添加自定义名称、表情符号等。 ```typescript const gt = new GT({ projectId: 'my-project-id', apiKey: 'my-api-key', targetLocale: 'es', customMapping: { 'en-US': { name: 'Mandarin', emoji: '🇫🇷' } } }); ``` *** ## 注意事项 * 所有参数都是可选的,但执行 API 操作时需要 `apiKey` 和 `projectId` * 构造函数会立即验证所有区域设置代码,若代码无效则抛出错误 * 自定义映射的优先级高于标准的 BCP 47 验证 ## 后续步骤 * 使用 [`setConfig`](/docs/core/class/set-config) 配置实例 * 使用 [`translate`](/docs/core/class/methods/translation/translate) 开始翻译 * 了解 [`GTConstructorParams` 类型](/docs/core/types/gt-constructor-params)