Class I18n

Hierarchy

  • I18n

Constructors

Properties

availableLocales: string[] = []

Set the available locales.

defaultSeparator: string

Set the default string separator. Defaults to ., as in scope.translation.

distanceOfTimeInWords: ((fromTime: DateTime, toTime: DateTime, options?: TimeAgoInWordsOptions) => string) = ...

Type declaration

enableFallback: boolean

Set if engine should fallback to the default locale when a translation is missing. Defaults to false.

When enabled, missing translations will first be looked for in less specific versions of the requested locale and if that fails by taking them from your I18n#defaultLocale.

interpolate: ((i18n: I18n, message: string, options: TranslateOptions) => string)

Type declaration

l: ((type: string, value: undefined | null | string | number | Date, options?: Dict) => string) = ...

Type declaration

    • (type: string, value: undefined | null | string | number | Date, options?: Dict): string
    • Alias

      localize

      Parameters

      • type: string
      • value: undefined | null | string | number | Date
      • Optional options: Dict

      Returns string

locales: Locales

The locale resolver registry.

See

Locales

missingBehavior: string

Set missing translation behavior.

  • message will display a message that the translation is missing.
  • guess will try to guess the string.
  • error will raise an exception whenever a translation is not defined.

See register for instructions on how to define your own behavior.

missingPlaceholder: MissingPlaceholderHandler

Return a missing placeholder message for given parameters.

missingTranslation: MissingTranslation

The missing translation behavior registry.

See

MissingTranslation

missingTranslationPrefix: string

If you use missingBehavior with 'message', but want to know that the string is actually missing for testing purposes, you can prefix the guessed string by setting the value here. By default, no prefix is used.

nullPlaceholder: NullPlaceholderHandler

Return a placeholder message for null values. Defaults to the same behavior as I18n.missingPlaceholder.

onChangeHandlers: OnChangeHandler[] = []

List of all onChange handlers.

p: ((count: number, scope: Scope, options?: TranslateOptions) => string) = ...

Type declaration

placeholder: RegExp

Set the placeholder format. Accepts {{placeholder}} and %{placeholder}.

pluralization: Pluralization

The pluralization behavior registry.

See

Pluralization

t: (<T>(scope: Scope, options?: TranslateOptions) => string | T) = ...

Type declaration

transformKey: ((key: string) => string)

Type declaration

    • (key: string): string
    • Transform keys. By default, it returns the key as it is, but allows for overriding. For instance, you can set a function to receive the camelcase key, and convert it to snake case.

      Parameters

      • key: string

      Returns string

translations: Dict = {}

Set the registered translations. The root key must always be the locale (and its variations with region).

Remember that no events will be triggered if you change this object directly. To trigger onchange events, you must perform updates either using I18n#store or I18n#update.

Accessors

  • get defaultLocale(): string
  • Return the default locale, using a explicit locale set using i18n.defaultLocale = locale, the default locale set using i18n.defaultLocale or the fallback, which is en.

    Returns

    The current locale.

    Returns string

  • set defaultLocale(newLocale: string): void
  • Set the default locale explicitly.

    Parameters

    • newLocale: string

      The new locale.

    Returns void

  • get locale(): string
  • Return the current locale, using a explicit locale set using i18n.locale = newLocale, the default locale set using i18n.defaultLocale or the fallback, which is en.

    Returns

    The current locale.

    Returns string

  • set locale(newLocale: string): void
  • Set the current locale explicitly.

    Parameters

    • newLocale: string

      The new locale.

    Returns void

  • get version(): number
  • Return the change version. This value is incremented whenever I18n#store or I18n#update is called, or when I18n#locale/I18n#defaultLocale is set.

    Returns number

Methods

  • Returns

    The found scope.

    Parameters

    • scope: Scope

      The scope lookup path.

    Returns any

  • Localize several values.

    You can provide the following scopes: currency, number, or percentage. If you provide a scope that matches the /^(date|time)/ regular expression then the value will be converted by using the I18n.toTime function. It will default to the value's toString function.

    If value is either null or undefined then an empty string will be returned, regardless of that localization type has been used.

    Returns

    The localized string.

    Parameters

    • type: string

      The localization type.

    • value: undefined | null | string | number | Date

      The value that must be localized.

    • Optional options: Dict

      The localization options.

    Returns string

  • Formats a number into a currency string (e.g., $13.65). You can customize the format in the using an options object.

    The currency unit and number formatting of the current locale will be used unless otherwise specified in the provided options. No currency conversion is performed. If the user is given a way to change their locale, they will also be able to change the relative value of the currency displayed with this helper.

    Example

    i18n.numberToCurrency(1234567890.5);
    // => "$1,234,567,890.50"

    i18n.numberToCurrency(1234567890.506);
    // => "$1,234,567,890.51"

    i18n.numberToCurrency(1234567890.506, { precision: 3 });
    // => "$1,234,567,890.506"

    i18n.numberToCurrency("123a456");
    // => "$123a456"

    i18n.numberToCurrency("123a456", { raise: true });
    // => raises exception ("123a456" is not a valid numeric value)

    i18n.numberToCurrency(-0.456789, { precision: 0 });
    // => "$0"

    i18n.numberToCurrency(-1234567890.5, { negativeFormat: "(%u%n)" });
    // => "($1,234,567,890.50)"

    i18n.numberToCurrency(1234567890.5, {
    unit: "&pound;",
    separator: ",",
    delimiter: "",
    });
    // => "&pound;1234567890,50"

    i18n.numberToCurrency(1234567890.5, {
    unit: "&pound;",
    separator: ",",
    delimiter: "",
    format: "%n %u",
    });
    // => "1234567890,50 &pound;"

    i18n.numberToCurrency(1234567890.5, { stripInsignificantZeros: true });
    // => "$1,234,567,890.5"

    i18n.numberToCurrency(1234567890.5, { precision: 0, roundMode: "up" });
    // => "$1,234,567,891"

    Returns

    The formatted number.

    Parameters

    • input: Numeric

      The number to be formatted.

    • options: Partial<FormatNumberOptions> = {}

      The formatting options. When defined, supersedes the default options defined by number.format and number.currency.*.

    Returns string

  • Formats a +number+ with grouped thousands using delimiter (e.g., 12,324). You can customize the format in the options parameter.

    Example

    i18n.numberToDelimited(12345678);
    // => "12,345,678"

    i18n.numberToDelimited("123456");
    // => "123,456"

    i18n.numberToDelimited(12345678.05);
    // => "12,345,678.05"

    i18n.numberToDelimited(12345678, { delimiter: "." });
    // => "12.345.678"

    i18n.numberToDelimited(12345678, { delimiter: "," });
    // => "12,345,678"

    i18n.numberToDelimited(12345678.05, { separator: " " });
    // => "12,345,678 05"

    i18n.numberToDelimited("112a");
    // => "112a"

    i18n.numberToDelimited(98765432.98, { delimiter: " ", separator: "," });
    // => "98 765 432,98"

    i18n.numberToDelimited("123456.78", {
    delimiterPattern: /(\d+?)(?=(\d\d)+(\d)(?!\d))/g,
    });
    // => "1,23,456.78"

    Returns

    The formatted number.

    Parameters

    Returns string

  • Convert a number into a readable representation.

    Example

    i18n.numberToHuman(123);
    // => "123"

    i18n.numberToHuman(1234);
    // => "1.23 Thousand"

    i18n.numberToHuman(12345);
    // => "12.3 Thousand"

    i18n.numberToHuman(1234567);
    // => "1.23 Million"

    i18n.numberToHuman(1234567890);
    // => "1.23 Billion"

    i18n.numberToHuman(1234567890123);
    // => "1.23 Trillion"

    i18n.numberToHuman(1234567890123456);
    // => "1.23 Quadrillion"

    i18n.numberToHuman(1234567890123456789);
    // => "1230 Quadrillion"

    i18n.numberToHuman(489939, { precision: 2 });
    // => "490 Thousand"

    i18n.numberToHuman(489939, { precision: 4 });
    // => "489.9 Thousand"

    i18n.numberToHuman(489939, { precision: 2, roundMode: "down" });
    // => "480 Thousand"

    i18n.numberToHuman(1234567, { precision: 4, significant: false });
    // => "1.2346 Million"

    i18n.numberToHuman(1234567, {
    precision: 1,
    separator: ",",
    significant: false,
    });
    // => "1,2 Million"

    i18n.numberToHuman(500000000, { precision: 5 });
    // => "500 Million"

    i18n.numberToHuman(12345012345, { significant: false });
    // => "12.345 Billion"

    Non-significant zeros after the decimal separator are stripped out by default (set stripInsignificantZeros to false to change that):

    i18n.numberToHuman(12.00001);
    // => "12"

    i18n.numberToHuman(12.00001, { stripInsignificantZeros: false });
    // => "12.0"

    You can also use your own custom unit quantifiers:

    i18n.numberToHuman(500000, units: { unit: "ml", thousand: "lt" });
    // => "500 lt"

    If in your I18n locale you have:

    ---
    en:
    distance:
    centi:
    one: "centimeter"
    other: "centimeters"
    unit:
    one: "meter"
    other: "meters"
    thousand:
    one: "kilometer"
    other: "kilometers"
    billion: "gazillion-distance"

    Then you could do:

    i18n.numberToHuman(543934, { units: "distance" });
    // => "544 kilometers"

    i18n.numberToHuman(54393498, { units: "distance" });
    // => "54400 kilometers"

    i18n.numberToHuman(54393498000, { units: "distance" });
    // => "54.4 gazillion-distance"

    i18n.numberToHuman(343, { units: "distance", precision: 1 });
    // => "300 meters"

    i18n.numberToHuman(1, { units: "distance" });
    // => "1 meter"

    i18n.numberToHuman(0.34, { units: "distance" });
    // => "34 centimeters"

    Returns

    The formatted number.

    Parameters

    • input: Numeric

      The number that will be formatted.

    • options: Partial<NumberToHumanOptions> = {}

      The formatting options. When defined, supersedes the default options stored at number.human.format.* and number.human.storage_units.*.

    Returns string

  • Convert a number into a readable size representation.

    Example

    i18n.numberToHumanSize(123)
    // => "123 Bytes"

    i18n.numberToHumanSize(1234)
    // => "1.21 KB"

    i18n.numberToHumanSize(12345)
    // => "12.1 KB"

    i18n.numberToHumanSize(1234567)
    // => "1.18 MB"

    i18n.numberToHumanSize(1234567890)
    // => "1.15 GB"

    i18n.numberToHumanSize(1234567890123)
    // => "1.12 TB"

    i18n.numberToHumanSize(1234567890123456)
    // => "1.1 PB"

    i18n.numberToHumanSize(1234567890123456789)
    // => "1.07 EB"

    i18n.numberToHumanSize(1234567, {precision: 2})
    // => "1.2 MB"

    i18n.numberToHumanSize(483989, precision: 2)
    // => "470 KB"

    i18n.numberToHumanSize(483989, {precision: 2, roundMode: "up"})
    // => "480 KB"

    i18n.numberToHumanSize(1234567, {precision: 2, separator: ","})
    // => "1,2 MB"

    i18n.numberToHumanSize(1234567890123, {precision: 5})
    // => "1.1228 TB"

    i18n.numberToHumanSize(524288000, {precision: 5})
    // => "500 MB"

    Returns

    The formatted number.

    Parameters

    • input: Numeric

      The number that will be formatted.

    • options: Partial<NumberToHumanSizeOptions> = {}

      The formatting options. When defined, supersedes the default options stored at number.human.storage_units.* and number.human.format.

    Returns string

  • Convert a number into a formatted percentage value.

    Example

    i18n.numberToPercentage(100);
    // => "100.000%"

    i18n.numberToPercentage("98");
    // => "98.000%"

    i18n.numberToPercentage(100, { precision: 0 });
    // => "100%"

    i18n.numberToPercentage(1000, { delimiter: ".", separator: "," });
    // => "1.000,000%"

    i18n.numberToPercentage(302.24398923423, { precision: 5 });
    // => "302.24399%"

    i18n.numberToPercentage(1000, { precision: null });
    // => "1000%"

    i18n.numberToPercentage("98a");
    // => "98a%"

    i18n.numberToPercentage(100, { format: "%n %" });
    // => "100.000 %"

    i18n.numberToPercentage(302.24398923423, { precision: 5, roundMode: "down" });
    // => "302.24398%"

    Returns

    The formatted number.

    Parameters

    • input: Numeric

      The number to be formatted.

    • options: Partial<NumberToPercentageOptions> = {}

      The formatting options. When defined, supersedes the default options stored at number.format and number.percentage.*.

    Returns string

  • Convert number to a formatted rounded value.

    Example

    i18n.numberToRounded(111.2345);
    // => "111.235"

    i18n.numberToRounded(111.2345, { precision: 2 });
    // => "111.23"

    i18n.numberToRounded(13, { precision: 5 });
    // => "13.00000"

    i18n.numberToRounded(389.32314, { precision: 0 });
    // => "389"

    i18n.numberToRounded(111.2345, { significant: true });
    // => "111"

    i18n.numberToRounded(111.2345, { precision: 1, significant: true });
    // => "100"

    i18n.numberToRounded(13, { precision: 5, significant: true });
    // => "13.000"

    i18n.numberToRounded(13, { precision: null });
    // => "13"

    i18n.numberToRounded(389.32314, { precision: 0, roundMode: "up" });
    // => "390"

    i18n.numberToRounded(13, {
    precision: 5,
    significant: true,
    stripInsignificantZeros: true,
    });
    // => "13"

    i18n.numberToRounded(389.32314, { precision: 4, significant: true });
    // => "389.3"

    i18n.numberToRounded(1111.2345, {
    precision: 2,
    separator: ",",
    delimiter: ".",
    });
    // => "1.111,23"

    Returns

    The formatted number.

    Parameters

    Returns string

  • Add a callback that will be executed whenever locale/defaultLocale changes, or I18n#store / I18n#update is called.

    Returns

    Return a function that can be used to unsubscribe the event handler.

    Parameters

    Returns (() => void)

      • (): void
      • Add a callback that will be executed whenever locale/defaultLocale changes, or I18n#store / I18n#update is called.

        Returns

        Return a function that can be used to unsubscribe the event handler.

        Returns void

  • Pluralize the given scope using the count value. The pluralized translation may have other placeholders, which will be retrieved from options.

    Returns

    The translated string.

    Parameters

    • count: number

      The counting number.

    • scope: Scope

      The translation scope.

    • Optional options: TranslateOptions

      The translation options.

    Returns string

  • Update translations by merging them. Newest translations will override existing ones.

    Returns

    Parameters

    • translations: Dict

      An object containing the translations that will be merged into existing translations.

    Returns void

  • Formats time according to the directives in the given format string. The directives begins with a percent (%) character. Any text not listed as a directive will be passed through to the output string.

    See

    strftime

    Returns

    The formatted date.

    Parameters

    • date: Date

      The date that will be formatted.

    • format: string

      The formatting string.

    • options: Partial<StrftimeOptions> = {}

      The formatting options.

    Returns string

  • Converts the array to a comma-separated sentence where the last element is joined by the connector word.

    Example

    i18n.toSentence(["apple", "banana", "pineapple"]);
    //=> apple, banana, and pineapple.

    Returns

    The joined string.

    Parameters

    • items: any[]

      The list of items that will be joined.

    • options: Partial<ToSentenceOptions> = {}

      The options.

    Returns string

  • Convert the given dateString into a formatted date.

    Returns

    The formatted date.

    Parameters

    • scope: Scope

      The formatting scope.

    • input: DateTime

      The string that must be parsed into a Date object.

    Returns string

  • Translate the given scope with the provided options.

    Returns

    The translated string.

    Type Parameters

    • T = string

    Parameters

    • scope: Scope

      The scope that will be used.

    • Optional options: TranslateOptions

      The options that will be used on the translation. Can include some special options like defaultValue, count, and scope. Everything else will be treated as replacement values.

    Returns string | T

  • You may want to update a part of your translations. This is a public interface for doing it so.

    If the provided path exists, it'll be replaced. Otherwise, a new node will be created. When running in strict mode, paths that doesn't already exist will raise an exception.

    Strict mode will also raise an exception if the override type differs from previous node type.

    Example

    i18n.update("en.number.format", {unit: "%n %u"});
    i18n.update("en.number.format", {unit: "%n %u"}, true);

    Returns

    Parameters

    • path: string

      The path that's going to be updated. It must include the language, as in en.messages.

    • override: any

      The new translation node.

    • options: {
          strict: boolean;
      } = ...

      Set options.

      • strict: boolean

        Raise an exception if path doesn't already exist, or if previous node's type differs from new node's type.

    Returns void

  • Executes function with given locale set. The locale will be changed only during the callback's execution, switching back to the previous value once it finishes (with or without errors).

    This is an asynchronous call, which means you must use await or you may end up with a race condition.

    Example

    await i18n.withLocale("pt", () => {
    console.log(i18n.t("hello"));
    });

    Returns

    Parameters

    • locale: string

      The temporary locale that will be set during the function's execution.

    • callback: (() => void)

      The function that will be executed with a temporary locale set.

        • (): void
        • Returns void

    Returns Promise<void>

Generated using TypeDoc