Command palette

@yasinsensoy/web

Web · APIs and utilities

Language (i18n)

Defines the main dictionary.

28 exports

Import

import {
  defineMessages,
  createI18n,
  enMessages,
  trMessages,
  formatMessage,
  createTranslator,
  mergeMessages,
  useT,
} from "@yasinsensoy/web";

Defines the main dictionary. Texts are stored as-is (with literal string types) so keys and {name} placeholders are inferred from the type. Library texts can be overridden in the ui namespace.

defineMessages(messages: T): T

Examples

// messages/en.ts
import { defineMessages } from "@yasinsensoy/web";

export default defineMessages({
  ui: { cancel: "Dismiss" },
  home: { title: "Welcome, {name}" },
  cart: { items: { one: "{count} item", other: "{count} items" } },
});

createI18n

function

Sets up the project's locale configuration. Called once, in a file that is not "use client"; server and client use the same object.

  • The default locale's dictionary is the type source: keys and placeholders are checked automatically. To carry the type to useT as well, add messages to the Register interface.
  • The library's own texts ("Close", "Cancel"…) live in the ui namespace of the same dictionary; Turkish is the default, enMessages is a ready English set, and any key can be overridden.
  • Other locales given via import() are loaded only when needed.
createI18n(config: { locales: S; defaultLocale: D; }): I18n<keyof S & string, AppMessages<Resolve<S[D]>>>

Examples

// i18n.ts
import { createI18n, defineMessages } from "@yasinsensoy/web";
import en from "./messages/en";

export const i18n = createI18n({
  defaultLocale: "en",
  locales: { en, tr: () => import("./messages/tr") },
});
export type Locale = (typeof i18n.locales)[number];

declare module "@yasinsensoy/web" {
  interface Register { messages: typeof en }
}

// app/[lang]/layout.tsx (server)
const messages = await i18n.load(lang);
<UIProvider locale={lang} messages={messages}>{children}</UIProvider>

// server component
const t = await i18n.getT(lang);
<h1>{t("home.title", { name: "Alice" })}</h1>

// client component
const t = useT();
<Button>{t("cart.checkout")}</Button>

enMessages

constant

All library texts, in English. Pass it to the dictionary's ui namespace; it is only bundled into projects that import it.

enMessages: UIMessages

Examples

// messages/en.ts
export default { ui: enMessages, home: { title: "Welcome" } } satisfies Translation;

trMessages

constant

All library texts, in Turkish. Components already use these by default; import this object to see and override all of them in the dictionary, or as a starting point for translating another language.

trMessages: UIMessages

Examples

defineMessages({ ui: { ...trMessages, cancel: "Vazgeç" }, home: {...} })

Fills {name} placeholders. Numbers and dates are formatted per locale (1,234.5, Nov 3, 2026); placeholders without a value are left as-is.

formatMessage(template: string, params: MessageParams, locale: string): string

Examples

formatMessage("{count} records", { count: 1234 }, "en-US"); // "1,234 records"

Creates a Translator (t) from a dictionary. Works on the server, the client and outside React. In Next.js, i18n.getT(locale) (createI18n) or useT on the client is usually used instead.

When namespace is given, keys are relative to that namespace: createTranslator(m, "en", "home")("title") → home.title.

createTranslator(messages: M, locale: string, namespace?: N): N extends string ? Translator<NamespaceMessages<M, N>> : Translator<M>

Examples

const t = createTranslator(en, "en-US");
t("home.title", { name: "Alice" });

Deep-merges dictionaries; later ones win. Used to fill missing translations from the default locale and by nested UIProviders.

mergeMessages(base: T, ...overrides: (object | undefined)[]): T

Examples

mergeMessages(en, tr); // keys missing in tr come from en

useT

function

Translator (t) for client components. The dictionary and locale come from the nearest UIProvider's messages and locale props; in server components use await i18n.getT(locale) (createI18n).

Keys and placeholders are checked against the dictionary given to Register. When namespace is given, keys are relative to it. The returned function stays the same until the locale or dictionary changes.

useT(namespace?: N): N extends string ? Translator<NamespaceMessages<RegisteredMessages, N>> : Translator

Examples

"use client";
const t = useT();
<Button>{t("cart.checkout")}</Button>
<p>{t("cart.items", { count })}</p>

const h = useT("home");
<h1>{h("title", { name })}</h1>

A locale's dictionary: a ready object or () => import("./en") that loads it.

type LocaleSource = Messages | (() => Promise<Messages | { readonly default: Messages; }>)

I18nConfig

interface

Settings for createI18n.

NameTypeDescription
localesReadonly<Record<string, LocaleSource>>Locales and their dictionaries. The default locale is usually given directly; others given as () => import("./messages/tr") are loaded only when needed and stay in a separate chunk.
defaultLocalestringDefault locale: used when no locale matches, and missing keys in other locales are filled from it.

I18n

interface

Result of createI18n.

NameTypeDescription
localesreadonly L[]Supported languages.
defaultLocaleLBase language.
isLocale(value: unknown): value is LWhether the value is a supported locale (e.g. [lang] in the URL).
match(request?: string | readonly string[] | null): LReturns the supported locale that best matches the requested one, or the default locale. Accepts an Accept-Language header ("en-US,en;q=0.9"), a list of locales (navigator.languages) or a single locale. If en-US is requested and only en exists, en is chosen.
load(locale?: string | null): Promise<M>Loads a locale's dictionary; missing keys are filled from the default locale. The result is cached. For an unsupported locale the closest one is chosen via I18n.match. Pass the result to UIProvider's messages.

A namespace's dictionary (behaves like a root other than ui).

type NamespaceMessages = N extends `${infer H}.${infer R}` ? H extends keyof M ? NamespaceMessages<NonNullable<M[H]>, R> : never : N extends keyof M ? NonNullable<M[N]> : never

Intl.PluralRules plural categories. one and other are enough for English and Turkish; languages such as Arabic or Russian use the others too.

type PluralCategory = "zero" | "one" | "two" | "few" | "many" | "other"

Text that varies with a number. The {count} placeholder and which form is chosen come from the number passed as t("key", { count }); selection follows the locale's rules (Intl.PluralRules), and other is used when no form matches.

Only an object made solely of plural categories (zero, one, two, few, many, other) that contains other counts as plural text, so do not put keys with only these names in a namespace.

type PluralMessage = { /** All other numbers; always required. */ other: string; } & { [K in Exclude<PluralCategory, "other">]?: string; }
NameTypeDescription
otherstringAll other numbers; always required.

Examples

cart: { one: "{count} item", other: "{count} items" }
// Turkish:
cart: { one: "{count} ürün", other: "{count} ürün" }

A text: plain text, plural text or a nested namespace.

type MessageValue = string | PluralMessage | MessageTree

MessageTree

interface

Nested namespaces; keys are joined with dots ("home.title").

The overridden part of the library texts. Plain texts are given directly; those of large components (kanban, dataGrid, eventCalendar, richText, mediaEditor) in their own namespaces.

type UIMessagesInput = { [K in keyof UIMessages]?: UIMessages[K] extends string ? string : Partial<UIMessages[K]>; }

Messages

interface

All texts of a locale: the app's own namespaces and the ui namespace for library texts.

NameTypeDescription
ui?UIMessagesInputTexts of the library components; provide only the ones you want to change.

Examples

{
  ui: { cancel: "Dismiss" },          // library text overridden
  home: { title: "Welcome, {name}" },
}

A value that can be passed to a {name} placeholder; numbers and dates are formatted per locale.

type MessageParam = string | number | Date

Placeholder values.

type MessageParams = Readonly<Record<string, MessageParam>>

Text keys in the registered dictionary ("home.title"). If Register is not extended, any string is accepted.

type MessageKey = IsLoose<M> extends true ? string : Leaves<AppPart<M>, "">

Namespaces in the registered dictionary ("home", "home.hero"); see useT.

type MessageNamespace = IsLoose<M> extends true ? string : Branches<AppPart<M>, "">

The value of a key in the dictionary.

type MessageAt = K extends `${infer H}.${infer R}` ? H extends keyof M ? MessageAt<NonNullable<M[H]>, R> : never : K extends keyof M ? NonNullable<M[K]> : never

Names of the {name} placeholders in a text.

type ParamNames = S extends `${string}{${infer N}}${infer R}` ? N | ParamNames<R> : never

Arguments after the key in a t(key, ...) call.

type TranslateArgs = [V] extends [string] ? [ParamNames<V>] extends [never] ? [params?: MessageParams] : [params: { readonly [N in ParamNames<V>]: MessageParam; }] : IsPlural<V> extends true ? [ params: { readonly count: number; } & { readonly [N in Exclude<ParamNames<V[keyof V]>, "count">]: MessageParam; } ] : [params?: MessageParams]

Translator

interface

Function that translates text from the dictionary. Keys and placeholders are inferred from the dictionary's type: a wrong key or missing value is a compile error.

NameTypeDescription
localestringLocale of the translation (BCP 47).
has(key: string): booleanWhether the key exists in the dictionary.

Examples

t("home.title", { name: "Alice" }); // "Welcome, Alice"
t("cart.items", { count: 3 });      // "3 items"

The project's dictionary type. Once messages is added to the Register interface, useT, createI18n and Translation use this type.

type RegisteredMessages = Register extends { messages: infer M; } ? M : Messages

Another locale's dictionary, shaped after the default locale's dictionary. All keys are required and every text must contain the default locale's placeholders ({name}); a missing key or forgotten placeholder is a compile error. Plural texts may use the locale's own categories. The ui namespace is optional.

By default the dictionary given to Register is used.

Extends: string extends keyof M> extends true ? Messages : TranslationOf<AppPart<M> ? true : false

NameTypeDescription
ui?UIMessagesInputLibrary texts; e.g. the ready English set enMessages.

Examples

// messages/tr.ts
import { trMessages, type Translation } from "@yasinsensoy/web";

export default {
  ui: trMessages,
  home: { title: "Hoş geldin, {name}" },
  cart: { items: { one: "{count} ürün", other: "{count} ürün" } },
} satisfies Translation;