Types
TranslationResult
translate() 方法返回的翻译结果类型定义
概述
TranslationResult 表示翻译操作的结果。
type TranslationResult = RequestSuccess | TranslationError;并联合类型
RequestSuccess
type RequestSuccess = TypedResult & {
locale: string;
reference: TranslationResultReference;
};翻译错误
type TranslationError = {
error: string;
code: number;
reference?: TranslationResultReference;
};示例
基础错误处理
import { GT, TranslationResult } from 'generaltranslation';
const gt = new GT({ apiKey: 'your-api-key' });
const result: TranslationResult = await gt.translate('Hello');
if ('error' in result) {
console.error(`翻译失败:${result.error}`);
} else {
console.log(`翻译结果:${result.translation}`);
}类型守卫
function isTranslationError(result: TranslationResult): result is TranslationError {
return 'error' in result;
}
if (isTranslationError(result)) {
// 错误处理
} else {
// 成功处理
}相关类型
TranslateManyResult- 批量翻译结果
本指南如何?