GT ClassMethodsTranslation

translate

GT translate 方法的 API 参考

概览

translate 方法是 GT 库中的核心翻译函数。 它利用 AI 驱动的翻译服务,将内容从源 locale 翻译为指定目标 locale。

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!"

该方法支持多种内容类型,包括纯文本、ICU 消息格式和 i18next 风格的消息,并可选传入元数据以提升翻译准确性。

需要身份验证: 在 GT 实例中必须配置 apiKey(或 devApiKey)及 projectId 才能使用 translate 方法。


参考

参数

translate 方法针对不同内容类型提供多种重载:

文本内容

Prop

Type

JSX 内容

Prop

Type

ICU 消息格式

Prop

Type

i18next 格式

Prop

Type

参数说明

参数说明
source待翻译的内容。可为纯文本、JSX 元素、ICU 消息或 i18next 消息
targetLocale目标语言的 BCP-47 语言代码(例如:“es”、“fr-CA”)
metadata可选的翻译上下文,包括上下文信息、标签和格式化选项

返回

Promise<TranslationResult | TranslationError>
  • TranslationResult: 包含译文内容及其元数据
  • TranslationError: 若翻译失败,包含错误信息

行为

内容类型检测

该方法会根据 source 参数自动检测内容类型:

  • 字符串:作为纯文本或 ICU 消息格式处理
  • JSX 元素:作为 React 风格的 JSX 内容处理
  • 对象:作为结构化消息格式处理

语言环境解析

  • 将依据 BCP-47 标准验证目标 locale
  • 如已配置,将应用自定义 locale 映射
  • API 请求将使用规范化的语言代码

上下文增强

当自定义映射为目标 locale 包含区域或脚本代码时,这些代码会自动添加到元数据中,以提升翻译的准确性。


示例

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

const result = await gt.translate('欢迎使用我们的应用程序', 'fr');
console.log(result); 
// "欢迎使用我们的应用程序"

说明

  • 将指定字符串翻译为目标 locale,并返回一个 Promise

下一步

本指南如何?