CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-typedoc

Create api documentation for TypeScript projects.

Pending
Overview
Eval results
Files

internationalization.mddocs/

Internationalization

Multi-language support system for localizing TypeDoc's output interface and messages, enabling documentation generation in multiple languages with full translation support.

Capabilities

Internationalization Class

Main internationalization manager that handles locale management, translation loading, and language switching.

/**
 * Internationalization manager for multi-language support
 */
class Internationalization {
  /** Current locale */
  readonly locale: string;
  /** Available translations */
  readonly translations: Map<string, Partial<TranslatableStrings>>;
  
  /**
   * Set active locale
   * @param locale - Locale code (e.g., "en", "de", "ja")
   */
  setLocale(locale: string): void;
  
  /**
   * Reset to default locale (English)
   */
  resetLocale(): void;
  
  /**
   * Add translations for a specific locale
   * @param locale - Locale code
   * @param translations - Translation strings
   */
  addTranslations(locale: string, translations: Partial<TranslatableStrings>): void;
  
  /**
   * Get translation proxy for current locale
   * @returns Translation proxy with type-safe access
   */
  proxy(): TranslationProxy;
  
  /**
   * Check if locale is supported
   * @param locale - Locale code to check
   * @returns True if locale has translations
   */
  hasLocale(locale: string): boolean;
  
  /**
   * Get available locales
   * @returns Array of supported locale codes
   */
  getAvailableLocales(): string[];
}

Usage Examples:

import { Application, Internationalization } from "typedoc";

const app = await Application.bootstrap({
  entryPoints: ["src/index.ts"],
  lang: "de", // Set German locale
});

const i18n = app.internationalization;

// Check current locale
console.log(`Current locale: ${i18n.locale}`);

// Add custom translations
i18n.addTranslations("de", {
  theme_implements: "Implementiert",
  theme_extended_by: "Erweitert von",
  theme_type_declaration: "Typ-Deklaration",
});

// Switch locale dynamically
i18n.setLocale("ja");
console.log(`Switched to: ${i18n.locale}`);

// Get translation proxy
const translations = i18n.proxy();
console.log(translations.theme_implements); // Returns localized string

Translation Function

Core translation function for converting translation keys to localized strings.

/**
 * Main translation function
 * @param key - Translation key
 * @param args - Optional arguments for string interpolation
 * @returns Localized string
 */
function i18n(key: TranslatedString, ...args: any[]): string;

Usage Examples:

import { i18n } from "typedoc";

// Basic translation
const implementsText = i18n("theme_implements");

// Translation with arguments
const parameterText = i18n("theme_parameter_name", "userId");

// Dynamic translation in templates
function renderProperty(property: any) {
  return `
    <div class="property">
      <h3>${property.name}</h3>
      <span class="type-label">${i18n("theme_type")}</span>
      <span class="type">${property.type}</span>
    </div>
  `;
}

Translation Types

Type-safe translation system with strongly-typed translation keys and proxy access.

/**
 * Type-safe translation string marker
 */
type TranslatedString = string & { __translatedBrand: never };

/**
 * Translation proxy providing type-safe access to translations
 */
interface TranslationProxy {
  /** Theme and UI translations */
  theme_implements: string;
  theme_indexable: string;
  theme_type_declaration: string;
  theme_constructor: string;
  theme_property: string;
  theme_method: string;
  theme_call_signature: string;
  theme_type_alias: string;
  theme_variable: string;
  theme_function: string;
  theme_module: string;
  theme_namespace: string;
  theme_class: string;
  theme_interface: string;
  theme_enum: string;
  theme_enum_member: string;
  theme_parameter: string;
  theme_type_parameter: string;
  theme_accessor: string;
  theme_get_signature: string;
  theme_set_signature: string;
  theme_reference: string;
  theme_document: string;
  
  /** Documentation structure */
  theme_hierarchy: string;
  theme_hierarchy_view: string;
  theme_on_this_page: string;
  theme_search: string;
  theme_menu: string;
  theme_copy_link: string;
  theme_permalink: string;
  theme_in: string;
  theme_generated_using_typedoc: string;
  
  /** Type information */
  theme_type: string;
  theme_value: string;
  theme_default_value: string;
  theme_inherited_from: string;
  theme_overrides: string;
  theme_implementation_of: string;
  theme_extended_by: string;
  theme_extended_types: string;
  theme_implemented_by: string;
  theme_implemented_types: string;
  
  /** Parameter and signature info */
  theme_parameters: string;
  theme_parameter_name: string;
  theme_returns: string;
  theme_type_parameters: string;
  theme_type_parameter_constraint: string;
  theme_type_parameter_default: string;
  
  /** Source and location */
  theme_defined_in: string;
  theme_source: string;
  
  /** Flags and modifiers */
  theme_optional: string;
  theme_readonly: string;
  theme_static: string;
  theme_private: string;
  theme_protected: string;
  theme_public: string;
  theme_abstract: string;
  theme_const: string;
  theme_rest: string;
  
  /** Navigation */
  theme_loading: string;
  theme_preparing_search_index: string;
  theme_search_results: string;
  theme_no_results_found: string;
  
  /** Settings and options */
  theme_settings: string;
  theme_member_visibility: string;
  theme_theme: string;
  theme_os: string;
  theme_light: string;
  theme_dark: string;
  theme_auto: string;
  
  /** Categories and grouping */
  kind_project: string;
  kind_module: string;
  kind_namespace: string;
  kind_enum: string;
  kind_enum_member: string;
  kind_variable: string;
  kind_function: string;
  kind_class: string;
  kind_interface: string;
  kind_constructor: string;
  kind_property: string;
  kind_method: string;
  kind_call_signature: string;
  kind_index_signature: string;
  kind_constructor_signature: string;
  kind_parameter: string;
  kind_type_literal: string;
  kind_type_parameter: string;
  kind_accessor: string;
  kind_get_signature: string;
  kind_set_signature: string;
  kind_object_literal: string;
  kind_type_alias: string;
  kind_reference: string;
  kind_document: string;
  
  /** Error messages */
  failed_to_find_packages: string;
  found_packages: string;
  no_entry_points_provided: string;
  unable_to_find_any_entry_points: string;
  provided_tsconfig_invalid: string;
  
  /** Reflection flags */
  flag_private: string;
  flag_protected: string;
  flag_public: string;
  flag_static: string;
  flag_external: string;
  flag_optional: string;
  flag_rest: string;
  flag_abstract: string;
  flag_const: string;
  flag_readonly: string;
  flag_inherited: string;
}

/**
 * Complete interface of all translatable strings in TypeDoc
 */
interface TranslatableStrings extends TranslationProxy {
  // Additional strings not included in proxy for internal use
  [key: string]: string;
}

Built-in Locale Support

TypeDoc includes built-in translations for several languages.

/**
 * Built-in supported locales
 */
type SupportedLocales = 
  | "en"    // English (default)
  | "de"    // German  
  | "ja"    // Japanese
  | "ko"    // Korean
  | "zh"    // Chinese (Simplified);

Usage Examples:

import { Application } from "typedoc";

// Generate documentation in German
const app = await Application.bootstrap({
  entryPoints: ["src/index.ts"],
  out: "docs-de",
  lang: "de",
});

// Generate documentation in Japanese
const japaneseApp = await Application.bootstrap({
  entryPoints: ["src/index.ts"], 
  out: "docs-ja",
  lang: "ja",
});

// Check what locales are available
const i18n = app.internationalization;
console.log("Available locales:", i18n.getAvailableLocales());

Custom Translation Loading

System for loading and managing custom translations from external sources.

/**
 * Utility functions for translation management
 */
namespace TranslationUtils {
  /**
   * Add translations from JSON file
   * @param i18n - Internationalization instance
   * @param locale - Target locale
   * @param filePath - Path to JSON translation file
   */
  function addTranslationsFromFile(
    i18n: Internationalization,
    locale: string,
    filePath: string
  ): Promise<void>;
  
  /**
   * Load translations from directory structure
   * @param i18n - Internationalization instance
   * @param translationsDir - Directory containing locale subdirectories
   */
  function loadTranslationsFromDirectory(
    i18n: Internationalization,
    translationsDir: string
  ): Promise<void>;
  
  /**
   * Validate translation completeness
   * @param translations - Translation object to validate
   * @param requiredKeys - Required translation keys
   * @returns Array of missing keys
   */
  function validateTranslations(
    translations: Partial<TranslatableStrings>,
    requiredKeys: (keyof TranslatableStrings)[]
  ): string[];
}

Usage Examples:

import { Application, TranslationUtils } from "typedoc";
import { writeFile, mkdir } from "fs/promises";

// Create custom translation file
const customTranslations = {
  theme_implements: "Реализует",
  theme_extended_by: "Расширяется",
  theme_type_declaration: "Объявление типа",
  theme_constructor: "Конструктор",
  theme_property: "Свойство",
  theme_method: "Метод",
  // ... more Russian translations
};

await mkdir("translations", { recursive: true });
await writeFile("translations/ru.json", JSON.stringify(customTranslations, null, 2));

// Load custom translations
const app = await Application.bootstrap();
await TranslationUtils.addTranslationsFromFile(
  app.internationalization,
  "ru", 
  "translations/ru.json"
);

// Set to custom locale
app.internationalization.setLocale("ru");

// Generate Russian documentation
const project = await app.convert();
if (project) {
  await app.generateDocs(project, "docs-ru");
}

Translation in Custom Themes

Integration of internationalization in custom themes and templates.

/**
 * Theme context with internationalization support
 */
interface ThemedRenderContext {
  /** Translation function bound to current locale */
  i18n: (key: TranslatedString, ...args: any[]) => string;
  /** Translation proxy for type-safe access */
  translations: TranslationProxy;
  /** Current locale code */
  locale: string;
}

Usage Examples:

import { DefaultTheme, i18n } from "typedoc";

class LocalizedTheme extends DefaultTheme {
  render(page: PageEvent<Reflection>, template: RenderTemplate<PageEvent<Reflection>>): string {
    // Add translation context to page
    const localizedPage = {
      ...page,
      i18n,
      translations: this.context.application.internationalization.proxy(),
      locale: this.context.application.internationalization.locale,
    };
    
    return super.render(localizedPage, template);
  }
}

// Custom template with translations
function renderClassPage(page: PageEvent<DeclarationReflection>) {
  const { reflection, i18n } = page;
  
  return `
    <div class="class-page">
      <h1>${reflection.name}</h1>
      
      ${reflection.implementedTypes?.length ? `
        <section>
          <h2>${i18n("theme_implements")}</h2>
          <ul>
            ${reflection.implementedTypes.map(type => 
              `<li>${type.toString()}</li>`
            ).join('')}
          </ul>
        </section>
      ` : ''}
      
      ${reflection.extendedBy?.length ? `
        <section>
          <h2>${i18n("theme_extended_by")}</h2>
          <ul>
            ${reflection.extendedBy.map(type => 
              `<li>${type.toString()}</li>`
            ).join('')}
          </ul>
        </section>
      ` : ''}
    </div>
  `;
}

Plugin Internationalization

Support for internationalizing custom plugins and extensions.

/**
 * Plugin with internationalization support
 */
abstract class InternationalizedPlugin extends AbstractComponent<Application, any> {
  /** Plugin translations */
  protected translations: Map<string, Partial<Record<string, string>>>;
  
  /**
   * Register plugin translations
   * @param locale - Locale code
   * @param translations - Plugin-specific translations
   */
  protected addPluginTranslations(locale: string, translations: Record<string, string>): void;
  
  /**
   * Get localized string for plugin
   * @param key - Translation key
   * @param args - Optional arguments
   * @returns Localized string
   */
  protected t(key: string, ...args: any[]): string;
}

Usage Examples:

import { InternationalizedPlugin } from "typedoc";

class CustomPlugin extends InternationalizedPlugin {
  initialize() {
    // Add plugin-specific translations
    this.addPluginTranslations("en", {
      "custom_feature_title": "Custom Feature",
      "custom_feature_description": "This is a custom feature",
      "custom_error_message": "Custom error occurred",
    });
    
    this.addPluginTranslations("de", {
      "custom_feature_title": "Benutzerdefinierte Funktion",
      "custom_feature_description": "Dies ist eine benutzerdefinierte Funktion",
      "custom_error_message": "Benutzerdefinierter Fehler aufgetreten",
    });
    
    // Use translations in plugin logic
    this.listenTo(this.owner, "beginRender", () => {
      console.log(this.t("custom_feature_title"));
    });
  }
}

Configuration Options

Language Configuration

/**
 * Language-related configuration options
 */
interface LanguageOptions {
  /** Primary locale for documentation */
  lang: string;
  /** Additional locales to generate */
  locales: string[];
  /** Custom translation directory */
  translationsDir?: string;
  /** Fallback locale for missing translations */
  fallbackLocale?: string;
}

Usage Examples:

import { Application } from "typedoc";

// Multi-language documentation generation
const app = await Application.bootstrap({
  entryPoints: ["src/index.ts"],
  out: "docs",
  lang: "en",
  locales: ["en", "de", "ja", "zh"],
  translationsDir: "./custom-translations",
  fallbackLocale: "en",
});

// This will generate separate documentation for each locale
const project = await app.convert();
if (project) {
  for (const locale of ["en", "de", "ja", "zh"]) {
    app.internationalization.setLocale(locale);
    await app.generateDocs(project, `docs/${locale}`);
  }
}

Error Handling

The internationalization system handles various error conditions:

  • Missing Translations: Fallback to default locale, logging of missing keys
  • Invalid Locales: Validation of locale codes, fallback behavior
  • File Loading: Translation file reading errors, JSON parsing failures
  • Memory Management: Large translation datasets, memory optimization
  • Plugin Conflicts: Conflicting translation keys, namespace isolation

All internationalization errors are logged with context about the locale and translation key for debugging.

Install with Tessl CLI

npx tessl i tessl/npm-typedoc

docs

application.md

configuration.md

converter.md

index.md

internationalization.md

models.md

output.md

serialization.md

tile.json