or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

date-time-formatting.mddisplay-name-formatting.mdindex.mdintl-instance.mdlist-formatting.mdmessage-formatting.mdnumber-formatting.mdrelative-time-pluralization.mdutility-functions.md
tile.json

index.mddocs/

@formatjs/intl

@formatjs/intl is a comprehensive internationalization library providing APIs to format dates, numbers, and strings, including pluralization and handling translations. It serves as a meta-package that aggregates various FormatJS utilities, offering unified formatting capabilities with extensive locale support and polyfill integration.

Package Information

  • Package Name: @formatjs/intl
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @formatjs/intl

Core Imports

import { createIntl, defineMessage, defineMessages } from "@formatjs/intl";

For individual formatters:

import { 
  formatDate, 
  formatDateToParts,
  formatTime,
  formatTimeToParts,
  formatDateTimeRange,
  formatNumber, 
  formatNumberToParts,
  formatMessage, 
  formatList,
  formatListToParts,
  formatDisplayName,
  formatRelativeTime,
  formatPlural
} from "@formatjs/intl";

For utilities and cache management:

import { 
  createIntlCache,
  createFormatters,
  filterProps,
  getNamedFormat,
  DEFAULT_INTL_CONFIG 
} from "@formatjs/intl";

For error handling:

import {
  IntlError,
  IntlErrorCode,
  UnsupportedFormatterError,
  InvalidConfigError,
  MissingDataError,
  IntlFormatError,
  MessageFormatError,
  MissingTranslationError
} from "@formatjs/intl";

CommonJS:

const { createIntl, defineMessage, formatDate } = require("@formatjs/intl");

Basic Usage

import { createIntl } from "@formatjs/intl";

// Create intl instance with configuration
const intl = createIntl({
  locale: 'en-US',
  messages: {
    greeting: 'Hello {name}!',
    itemCount: 'You have {count, plural, =0 {no items} one {one item} other {# items}}'
  }
});

// Format messages
const greeting = intl.formatMessage(
  { id: 'greeting' }, 
  { name: 'Alice' }
);

// Format numbers and dates
const price = intl.formatNumber(1234.56, { 
  style: 'currency', 
  currency: 'USD' 
});
const date = intl.formatDate(new Date(), { 
  year: 'numeric', 
  month: 'long', 
  day: 'numeric' 
});

Architecture

@formatjs/intl is built around several key components:

  • Intl Instance: Central object (createIntl) providing all formatting methods with shared configuration
  • Individual Formatters: Standalone functions for specific formatting needs without instance creation
  • Message System: ICU MessageFormat integration with pluralization, gender, and rich text support
  • Caching Layer: Memoized formatter instances to prevent memory leaks and improve performance
  • Type Safety: Full TypeScript support with configurable message ID types and rich text element generics
  • Polyfill Integration: Automatic detection and graceful fallback for missing Intl APIs

Capabilities

Intl Instance Creation

Create configured intl instances that provide all formatting methods with shared locale and message configuration.

function createIntl<T = string>(
  config: IntlConfig<T>,
  cache?: IntlCache
): IntlShape<T>;

interface IntlConfig<T = string> {
  locale: string;
  messages?: Record<string, string> | Record<string, MessageFormatElement[]>;
  timeZone?: string;
  formats?: CustomFormats;
  defaultLocale?: string;
  defaultFormats?: CustomFormats;
  defaultRichTextElements?: Record<string, FormatXMLElementFn<T>>;
  fallbackOnEmptyString?: boolean;
  onError?: OnErrorFn;
  onWarn?: OnWarnFn;
}

Intl Instance

Message Formatting

ICU MessageFormat integration with pluralization, gender, and rich text element support for comprehensive internationalization.

function formatMessage(
  config: ResolvedIntlConfig,
  formatters: Formatters,
  descriptor: MessageDescriptor,
  values?: Record<string, PrimitiveType | FormatXMLElementFn>,
  opts?: IntlMessageFormatOptions
): string | Array<string | T> | T;

function defineMessage<T>(msg: T): T;
function defineMessages<K, T, U>(msgs: U): U;

Message Formatting

Date and Time Formatting

Comprehensive date and time formatting with timezone support, custom formats, parts-based output, and date range formatting.

function formatDate(
  config: ResolvedIntlConfig,
  getDateTimeFormat: Formatters['getDateTimeFormat'],
  value: Date | string | number,
  options?: FormatDateOptions
): string;

function formatTime(
  config: ResolvedIntlConfig,
  getDateTimeFormat: Formatters['getDateTimeFormat'],
  value: Date | string | number,
  options?: FormatDateOptions
): string;

function formatDateToParts(
  config: ResolvedIntlConfig,
  getDateTimeFormat: Formatters['getDateTimeFormat'],
  value: Date | string | number,
  options?: FormatDateOptions
): Intl.DateTimeFormatPart[];

function formatTimeToParts(
  config: ResolvedIntlConfig,
  getDateTimeFormat: Formatters['getDateTimeFormat'],
  value: Date | string | number,
  options?: FormatDateOptions
): Intl.DateTimeFormatPart[];

function formatDateTimeRange(
  config: ResolvedIntlConfig,
  getDateTimeFormat: Formatters['getDateTimeFormat'],
  from: Date | string | number,
  to: Date | string | number,
  options?: FormatDateOptions
): string;

Date and Time Formatting

Number Formatting

Number formatting with support for currencies, units, compact notation, and custom number systems.

function formatNumber(
  config: ResolvedIntlConfig,
  getNumberFormat: Formatters['getNumberFormat'],
  value: number | bigint,
  options?: FormatNumberOptions
): string;

function formatNumberToParts(
  config: ResolvedIntlConfig,
  getNumberFormat: Formatters['getNumberFormat'],
  value: number | bigint, 
  options?: FormatNumberOptions
): Intl.NumberFormatPart[];

Number Formatting

List Formatting

Format arrays of items with locale-appropriate conjunctions, disjunctions, unit formatting, and parts-based output.

function formatList<T>(
  config: { locale: string; onError: OnErrorFn },
  getListFormat: Formatters['getListFormat'],
  values: readonly (string | T)[],
  options?: FormatListOptions
): string | T | (string | T)[];

function formatListToParts<T>(
  config: { locale: string; onError: OnErrorFn },
  getListFormat: Formatters['getListFormat'],
  values: readonly (string | T)[],
  options?: FormatListOptions
): Part[];

List Formatting

Display Name Formatting

Format display names for languages, regions, scripts, and currencies with fallback handling.

function formatDisplayName(
  config: { locale: string; onError: OnErrorFn },
  getDisplayNames: Formatters['getDisplayNames'],
  value: string,
  options: FormatDisplayNameOptions
): string | undefined;

Display Name Formatting

Relative Time and Pluralization

Format relative time expressions and handle pluralization rules for different locales.

function formatRelativeTime(
  config: ResolvedIntlConfig,
  getRelativeTimeFormat: Formatters['getRelativeTimeFormat'],
  value: number,
  unit?: Intl.RelativeTimeFormatUnit,
  options?: FormatRelativeTimeOptions
): string;

function formatPlural(
  config: { locale: string; onError: OnErrorFn },
  getPluralRules: Formatters['getPluralRules'],
  value: number,
  options?: FormatPluralOptions
): LDMLPluralRule;

Relative Time and Pluralization

Utility Functions

Cache management, configuration utilities, and performance optimization helpers.

function createIntlCache(): IntlCache;
function createFormatters(cache?: IntlCache): Formatters;
function filterProps<T, K>(props: T, allowlist: K[], defaults?: Partial<T>): Pick<T, K>;
function getNamedFormat<T>(formats: CustomFormats, type: T, name: string, onError: OnErrorFn): any;

Utility Functions

Error Handling

Comprehensive error handling with typed error classes and error codes for robust internationalization workflows.

class IntlError<T extends IntlErrorCode = IntlErrorCode> extends Error {
  public code: T;
  constructor(code: T, message: string, exception?: Error | unknown);
}

class UnsupportedFormatterError extends IntlError<IntlErrorCode.UNSUPPORTED_FORMATTER> {}
class InvalidConfigError extends IntlError<IntlErrorCode.INVALID_CONFIG> {}
class MissingDataError extends IntlError<IntlErrorCode.MISSING_DATA> {}
class IntlFormatError extends IntlError<IntlErrorCode.FORMAT_ERROR> {}
class MessageFormatError extends IntlError<IntlErrorCode.FORMAT_ERROR> {}
class MissingTranslationError extends IntlError<IntlErrorCode.MISSING_TRANSLATION> {}

enum IntlErrorCode {
  FORMAT_ERROR = "FORMAT_ERROR",
  UNSUPPORTED_FORMATTER = "UNSUPPORTED_FORMATTER",
  INVALID_CONFIG = "INVALID_CONFIG", 
  MISSING_DATA = "MISSING_DATA",
  MISSING_TRANSLATION = "MISSING_TRANSLATION"
}

Core Types

interface IntlShape<T = string> extends ResolvedIntlConfig<T>, IntlFormatters<T> {
  formatters: Formatters;
}

interface MessageDescriptor {
  id?: string;
  description?: string | object;
  defaultMessage?: string | MessageFormatElement[];
}

interface IntlCache {
  dateTime: Record<string, DateTimeFormat>;
  number: Record<string, Intl.NumberFormat>;
  message: Record<string, IntlMessageFormat>;
  relativeTime: Record<string, Intl.RelativeTimeFormat>;
  pluralRules: Record<string, Intl.PluralRules>;
  list: Record<string, IntlListFormat>;
  displayNames: Record<string, DisplayNames>;
}

interface CreateIntlFn<
  T = string,
  C extends IntlConfig<T> = IntlConfig<T>,
  S extends IntlShape<T> = IntlShape<T>
> {
  (config: C, cache?: IntlCache): S;
}

enum IntlErrorCode {
  FORMAT_ERROR = "FORMAT_ERROR",
  UNSUPPORTED_FORMATTER = "UNSUPPORTED_FORMATTER", 
  INVALID_CONFIG = "INVALID_CONFIG",
  MISSING_DATA = "MISSING_DATA",
  MISSING_TRANSLATION = "MISSING_TRANSLATION"
}

class IntlError<T extends IntlErrorCode = IntlErrorCode> extends Error {
  public code: T;
  constructor(code: T, message: string, exception?: Error | unknown);
}

interface Formatters {
  getDateTimeFormat(...args: ConstructorParameters<typeof Intl.DateTimeFormat>): DateTimeFormat;
  getNumberFormat(locales?: string | string[], opts?: NumberFormatOptions): Intl.NumberFormat;
  getMessageFormat(...args: ConstructorParameters<typeof IntlMessageFormat>): IntlMessageFormat;
  getRelativeTimeFormat(...args: ConstructorParameters<typeof Intl.RelativeTimeFormat>): Intl.RelativeTimeFormat;
  getPluralRules(...args: ConstructorParameters<typeof Intl.PluralRules>): Intl.PluralRules;
  getListFormat(...args: ConstructorParameters<typeof IntlListFormat>): IntlListFormat;
  getDisplayNames(...args: ConstructorParameters<typeof DisplayNames>): DisplayNames;
}

interface IntlFormatters<TBase = unknown> {
  formatDateTimeRange(from: Date, to: Date, opts?: FormatDateOptions): string;
  formatDate(value: Date | number | string, opts?: FormatDateOptions): string;
  formatTime(value: Date | number | string, opts?: FormatDateOptions): string;
  formatDateToParts(value: Date | number | string, opts?: FormatDateOptions): Intl.DateTimeFormatPart[];
  formatTimeToParts(value: Date | number | string, opts?: FormatDateOptions): Intl.DateTimeFormatPart[];
  formatNumber(value: number, opts?: FormatNumberOptions): string;
  formatNumberToParts(value: number, opts?: FormatNumberOptions): Intl.NumberFormatPart[];
  formatMessage(descriptor: MessageDescriptor, values?: Record<string, any>, opts?: IntlMessageFormatOptions): string;
  $t: IntlFormatters<TBase>['formatMessage'];
  formatRelativeTime(value: number, unit?: Intl.RelativeTimeFormatUnit, opts?: FormatRelativeTimeOptions): string;
  formatPlural(value: number, opts?: FormatPluralOptions): ReturnType<Intl.PluralRules['select']>;
  formatList(values: ReadonlyArray<string>, opts?: FormatListOptions): string;
  formatListToParts(values: ReadonlyArray<string>, opts?: FormatListOptions): Part[];
  formatDisplayName(value: string, opts: FormatDisplayNameOptions): string | undefined;
}

interface ResolvedIntlConfig<T = string> extends IntlConfig<T> {
  locale: string;
  timeZone?: string;
  fallbackOnEmptyString: boolean;
  formats: CustomFormats;
  messages: Record<string, string> | Record<string, MessageFormatElement[]>;
  defaultLocale: string;
  defaultFormats: CustomFormats;
  onError: OnErrorFn;
  onWarn?: OnWarnFn;
}

type OnErrorFn = (err: IntlError) => void;
type OnWarnFn = (warning: string) => void;
type LDMLPluralRule = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other';