i18next
- Version 27.2.10
- Published
- 624 kB
- No dependencies
- MIT license
Install
npm i i18nextyarn add i18nextpnpm add i18nextOverview
i18next internationalization framework
Index
Variables
Functions
Classes
Interfaces
InitOptions
- appendNamespaceToCIMode
- appendNamespaceToMissingKey
- cacheInBuiltFormats
- cleanCode
- contextSeparator
- debug
- defaultNS
- enableSelector
- fallbackLng
- fallbackNS
- ignoreJSONStructure
- initAsync
- interpolation
- joinArrays
- keySeparator
- lng
- load
- lowerCaseLng
- maxParallelReads
- maxRetries
- missingInterpolationHandler
- missingKeyHandler
- missingKeyNoValueFallbackToKey
- nonExplicitSupportedLngs
- ns
- nsSeparator
- overloadTranslationOptionHandler()
- parseMissingKeyHandler()
- partialBundledLanguages
- pluralSeparator
- postProcess
- postProcessPassResolved
- preload
- react
- resources
- retryTimeout
- returnDetails
- returnedObjectHandler()
- returnEmptyString
- returnNull
- returnObjects
- saveMissing
- saveMissingPlurals
- saveMissingTo
- supportedLngs
- updateMissing
Type Aliases
- AppendKeyPrefix
- AppendNamespace
- ApplyKeyPrefix
- ApplyTarget
- Callback
- CallbackError
- ConstrainTarget
- ContextOfKey
- DeepUnwrapPlural
- DefaultNamespace
- DefaultTReturn
- EffectiveKPrefix
- FallbackLng
- FallbackResourcesOf
- FilterKeys
- FilterKeysByContext
- FilterKeysObject
- FlatNamespace
- FormatFunction
- GetSource
- InterpolationMap
- JoinKeys
- KeyFromSelectorFn
- KeyPrefix
- KeyPrefixSelector
- KeysBuilder
- KeysBuilderWithoutReturnObjects
- KeysBuilderWithReturnObjects
- KeysByTOptions
- KeysWithoutReturnObjects
- KeysWithReturnObjects
- KeyWithContext
- ModuleType
- MultiReadCallback
- Namespace
- NsArg
- NsByTOptions
- NsResource
- ParseActualValue
- ParseInterpolationEntries
- ParseInterpolationValues
- ParseKeys
- ParseKeysByFallbackNs
- ParseKeysByKeyPrefix
- ParseKeysByNamespaces
- ParseKeysWithoutVariables
- ParseTReturn
- ParseTReturnPlural
- ParseTReturnPluralOrdinal
- ParseTReturnWithFallback
- PickNamespaces
- PluginOptions
- PluralSuffix
- PluralValue
- ProcessReturnValue
- ReadCallback
- ResourceKey
- ResourceKeys
- Resources
- Select
- SelectorKey
- SelectorParam
- SelectorReturn
- SelectorReturnSource
- TFunctionDetailedResult
- TFunctionProcessReturnValue
- TFunctionReturn
- TFunctionReturnOptionalDetails
- TFunctionSignature
- TOptions
- TReturnOptionalNull
- TReturnOptionalObjects
- TrimSpaces
- TypeOptions
- WithOrWithoutPlural
Variables
variable changeLanguage
const changeLanguage: any;variable createInstance
const createInstance: any;variable dir
const dir: any;variable exists
const exists: { <K extends string>(key: K, options?: TOptions<$Dictionary<unknown>>): key is K & string & { readonly [$SelectorKeyBrand]: unique symbol }; (key: string | string[], options?: TOptions<$Dictionary<unknown>>): boolean;};variable getFixedT
const getFixedT: <Ns extends Namespace<string>>() => any;variable hasLoadedNamespace
const hasLoadedNamespace: any;variable i18next
const i18next: i18n;variable init
const init: { (callback?: Callback): Promise<TFunction<'translation', undefined>>; <T>(options: InitOptions<T>, callback?: Callback): Promise< TFunction<'translation', undefined> >;};variable keyFromSelector
const keyFromSelector: KeyFromSelectorFn;variable loadLanguages
const loadLanguages: any;variable loadNamespaces
const loadNamespaces: any;variable loadResources
const loadResources: (callback?: (err: any) => void) => void;variable reloadResources
const reloadResources: any;variable setDefaultNamespace
const setDefaultNamespace: any;variable t
const t: TFunction<['translation', ...string[]], undefined>;variable TKPrefixFn
const TKPrefixFn: any;variable use
const use: <T extends Module>(module: T | NewableModule<T> | Newable<T>) => i18n;Functions
function isSafeLanguageCode
isSafeLanguageCode: (code: unknown) => boolean;Whether a language code has the shape i18next accepts from outside (
lng,changeLanguage(), language detectors) without it being configured: letters, digits,-,_,@and.(no..), at most 128 characters, not a prototype key. Since v27 other codes are refused unless they are listed insupportedLngs,fallbackLng,preloador the resources. Not a BCP 47 check:'en_US'and'sr@latin'pass. For plugins that take a language from a request, a URL or storage. Since v26.7.0.
Classes
class ResourceStore
class ResourceStore {}constructor
constructor(data: Resource, options: InitOptions<object>);property data
data: Resource;property options
options: InitOptions<object>;method off
off: ( event: 'added' | 'removed', callback?: (lng: string, ns: string) => void) => void;Remove event listener removes all callback when callback not specified
method on
on: ( event: 'added' | 'removed', callback: (lng: string, ns: string) => void) => void;Gets fired when resources got added or removed
method once
once: ( event: 'added' | 'removed', callback: (lng: string, ns: string) => void) => this;Subscribe to an event, but only once. The listener is removed after the first call.
Interfaces
interface BackendModule
interface BackendModule<Options = object> extends Module {}Used to load data for i18next. Can be provided as a singleton or as a prototype constructor (preferred for supporting multiple instances of i18next). For singleton set property
typeto'backend'For a prototype constructor set static property.
property callbackApi
callbackApi?: boolean;Declares how i18next calls
readandcreate(since v26.7.0; as an instance or static property): -true:read(language, namespace, callback)andcreate(languages, namespace, key, fallbackValue, callback, options)-false:read(language, namespace)andcreate(languages, namespace, key, fallbackValue, options)return a promise or a valueLeft out, i18next guesses it from the number of parameters, which is deprecated.
property type
type: 'backend';method create
create: ( languages: readonly string[], namespace: string, key: string, fallbackValue: string, callbackOrOptions?: any, options?: any) => void;Save the missing translation. Called as
create(languages, namespace, key, fallbackValue, callback, options)withcallbackApi: true, ascreate(languages, namespace, key, fallbackValue, options)returning a promise or a value withcallbackApi: false.optionsare the options of thetcall plusisUpdate.
method init
init: ( services: Services, backendOptions: Options, i18nextOptions: InitOptions) => void;method read
read: (language: string, namespace: string, callback: ReadCallback) => void;Load a namespace. With
callbackApi: false, implement it asread(language, namespace)returning the data or a promise of it (thevoidreturn type accepts both forms).
method readMulti
readMulti: ( languages: readonly string[], namespaces: readonly string[], callback: MultiReadCallback) => void;Load multiple languages and namespaces. For backends supporting multiple resources loading. With
callbackApi: false, implement it asreadMulti(languages, namespaces)returning the data or a promise of it.
method save
save: (language: string, namespace: string, data: ResourceLanguage) => void;Store the translation. For backends acting as cache layer
interface Branded
interface Branded<Ns extends Namespace> {}property $TFunctionBrand
$TFunctionBrand: $IsResourcesDefined extends true ? `${Ns extends readonly any[] ? Ns[0] : Ns}` : never;interface CloneOptions
interface CloneOptions extends InitOptions {}property forkResourceStore
forkResourceStore?: boolean;Will create a new instance of the resource store and import the existing translation resources. This way it will not shared the resource store instance. false
interface CustomInstanceExtensions
interface CustomInstanceExtensions {}interface CustomPluginOptions
interface CustomPluginOptions {}This interface can be augmented by users to add types to
i18nextdefault PluginOptions.
interface CustomTypeOptions
interface CustomTypeOptions {}This interface can be augmented by users to add types to
i18nextdefault TypeOptions.Usage:
// i18next.d.tsimport 'i18next';declare module 'i18next' {interface CustomTypeOptions {defaultNS: 'custom';returnNull: false;returnObjects: false;nsSeparator: ':';keySeparator: '.';allowObjectInHTMLChildren: false;resources: {custom: {foo: 'foo';};};}}
interface ExistsFunction
interface ExistsFunction< TKeys extends string = string, TInterpolationMap extends object = $Dictionary> {}Uses similar args as the t function and returns true if a key exists.
Note: this shape intentionally does not include a type-guard overload so it remains easy to assign arrow functions to. The type guard narrowing to SelectorKey is declared directly on
i18n.existsinstead. If you need narrowing in your own code, calli18next.existsdirectly or forward the function by reference (e.g. `const exists: typeof i18next.exists = i18next.exists`). Wrapping it in an arrow function will lose the narrowing — there is currently no way to keep type-guard narrowing through an arrow-function wrapper, which is whyExistsFunctiondeliberately omits the predicate overload.
call signature
(key: TKeys | TKeys[], options?: TOptions<TInterpolationMap>): boolean;interface FallbackLngObjList
interface FallbackLngObjList {}index signature
[language: string]: readonly string[];interface Formatter
interface Formatter {}property format
format: FormatFunction;method add
add: ( name: string, fc: (value: any, lng: string | undefined, options: any) => string) => void;method addCached
addCached: ( name: string, fc: (lng: string | undefined, options: any) => (value: any) => string) => void;method init
init: (services: Services, i18nextOptions: InitOptions) => void;interface FormatterModule
interface FormatterModule extends Module, Formatter {}property type
type: 'formatter';interface i18n
interface i18n extends CustomInstanceExtensions {}property exists
exists: { <K extends string>(key: K, options?: TOptions): key is K & SelectorKey; (key: string | string[], options?: TOptions): boolean;};Uses similar args as the t function and returns true if a key exists. Acts as a type guard on single-key calls, narrowing the key to SelectorKey so it can be passed to
t().
property modules
modules: Modules;List of modules used
property services
services: Services;Internal container for all used plugins and implementation details like languageUtils, pluralResolvers, etc.
property store
store: ResourceStore;Internal container for translation resources
property t
t: TFunction< [ ...$NormalizeIntoArray<DefaultNamespace>, ...Exclude< FlatNamespace, InferArrayValuesElseReturnType<DefaultNamespace> >[] ]>;method getDataByLanguage
getDataByLanguage: (lng: string) => { [key: string]: { [key: string]: string } };Returns a resource data by language.
method getFixedT
getFixedT: <Ns extends Namespace<string>>() => any;Returns a t function that defaults to given language or namespace. Both params could be arrays of languages or namespaces and will be treated as fallbacks in that case. On the returned function you can like in the t function override the languages or namespaces by passing them in options or by prepending namespace.
Accepts optional keyPrefix that will be automatically applied to returned t function.
Accepts optional fixedOpts:
scopeNsis the full namespace list the t function is bound to (react-i18next passes the namespaces ofuseTranslation); selector keys use it to find a namespace prefix, lookups still usens.
method init
init: { (callback?: Callback): Promise<TFunction>; <T>(options: InitOptions<T>, callback?: Callback): Promise< TFunction<'translation', undefined> >;};The default of the i18next module is an i18next instance ready to be initialized by calling init. You can create additional instances using the createInstance function.
Parameter options
Initial options.
Parameter callback
will be called after all translations were loaded or with an error when failed (in case of using a backend).
method loadResources
loadResources: (callback?: (err: any) => void) => void;method use
use: <T extends Module>(module: T | NewableModule<T> | Newable<T>) => this;The use function is there to load additional plugins to i18next. For available module see the plugins page and don't forget to read the documentation of the plugin.
Parameter module
Accepts a class or object
interface I18nFormatModule
interface I18nFormatModule extends Module {}Replaces the i18next message format with another syntax (like i18next-icu or i18next-mf2). Only one per i18next instance.
property handleAsObject
handleAsObject?: boolean;If true, i18next handles objects and arrays as usual (
returnObjects,joinArrays); else they go toparse
property type
type: 'i18nFormat';method addLookupKeys
addLookupKeys: ( finalKeys: string[], key: string, code: string, ns: string, options: any) => void;Called instead of the plural and context suffix lookup, for each language code and namespace; push more keys to
finalKeys(the last one is looked up first).
method getResource
getResource: (code: string, ns: string, key: string, options: any) => any;Replaces the lookup in the resource store
method init
init: (i18next: i18n) => void;Called on
i18next.initwith the instance; by convention the options are ini18next.options.i18nFormat
method parse
parse: ( res: any, options: any, lng: string | undefined, ns: string | undefined, key: string | undefined, info: { resolved: any }) => any;Called instead of interpolation and nesting; the return value goes through post processing and is returned by
t.resis the found value, or the default value or key if nothing was found.
interface InitOptions
interface InitOptions<T = object> extends PluginOptions<T> {}property appendNamespaceToCIMode
appendNamespaceToCIMode?: boolean;Prefixes the namespace to the returned key when using
cimodefalse
property appendNamespaceToMissingKey
appendNamespaceToMissingKey?: boolean;Appends namespace to missing key false
property cacheInBuiltFormats
cacheInBuiltFormats?: boolean;Initializes the internal formatter for the in-built formats as cached version. Can be set to false for this type of issues: https://github.com/i18next/i18next/issues/2227 true
property cleanCode
cleanCode?: boolean;Since v27, codes without a region get their canonical casing (
'EN'→'en'); aliases like'tl'or'iw'stay.falsekeeps them as they are, as before v27.truealso lower-cases a code that is not BCP 47.Deprecated
canonical codes are the default since v27 undefined
property contextSeparator
contextSeparator?: string;Char to split context from key '_'
property debug
debug?: boolean;Logs info level to console output. Helps finding issues with loading not working. false
property defaultNS
defaultNS?: string | false | readonly string[];Default namespace used if not passed to translation function 'translation'
property enableSelector
enableSelector?: false | true | 'optimize' | 'strict';Selector-API mode. Mirrors
CustomTypeOptions['enableSelector'].-
false(default): selector API disabled. -true/'optimize': selector resolution enabled. -'strict': require an explicit namespace as the first selector path segment in every call. The resolver always rewrites a leading namespace-matching segment as a namespace prefix.false
property fallbackLng
fallbackLng?: false | FallbackLng;Language to use if translations in user language are not available. Since v27 there is none by default;
'dev'was the default before. false
property fallbackNS
fallbackNS?: false | string | readonly string[];String or array of namespaces to lookup key if not found in given namespace. false
property ignoreJSONStructure
ignoreJSONStructure?: boolean;Automatically lookup for a flat key if a nested key is not found an vice-versa true
property initAsync
initAsync?: boolean;Triggers resource loading in init function inside a setTimeout (default async behaviour). Set it to false if your backend loads resources sync - that way calling i18next.t after init is possible without relaying on the init callback. true
property interpolation
interpolation?: InterpolationOptions;See Also
https://www.i18next.com/translation-function/interpolation
property joinArrays
joinArrays?: false | string;Char, eg. '\n' that arrays will be joined by false
property keySeparator
keySeparator?: false | string;Char to separate keys '.'
property lng
lng?: string;Language to use (overrides language detection) undefined
property load
load?: 'all' | 'currentOnly' | 'languageOnly';Language codes to lookup, given set language is 'en-US' and fallbackLng 'dev': 'all' --> ['en-US', 'en', 'dev'], 'currentOnly' --> 'en-US', 'languageOnly' --> 'en' 'all'
property lowerCaseLng
lowerCaseLng?: boolean;Language will be lowercased eg. en-US --> en-us false
property maxParallelReads
maxParallelReads?: number;Limit parallelism of calls to backend This is needed to prevent trying to open thousands of sockets or file descriptors, which can cause failures and actually make the entire process take longer. 10
property maxRetries
maxRetries?: number;The maximum number of retries to perform. Note that retries are only performed when a request has no response and throws an error. The default value is used if value is set below 0. 5
property missingInterpolationHandler
missingInterpolationHandler?: ( text: string, value: any, options: InitOptions) => any;Gets called in case a interpolation value is undefined. This method will not be called if the value is empty string or null noop
property missingKeyHandler
missingKeyHandler?: | false | (( lngs: readonly string[], ns: string, key: string, fallbackValue: string, updateMissing: boolean, options: any ) => void);Used for custom missing key handling (needs saveMissing set to true!) false
property missingKeyNoValueFallbackToKey
missingKeyNoValueFallbackToKey?: boolean;Used to not fallback to the key as default value, when using saveMissing functionality. i.e. when using with i18next-http-backend this will result in having a key with an empty string value. false
property nonExplicitSupportedLngs
nonExplicitSupportedLngs?: boolean;If true will pass eg. en-US if finding en in supportedLngs false
property ns
ns?: string | readonly string[];String or array of namespaces to load 'translation'
property nsSeparator
nsSeparator?: false | string;Char to split namespace from key ':'
property partialBundledLanguages
partialBundledLanguages?: boolean;Allow initializing with bundled resources while using a backend to load non bundled ones. false
property pluralSeparator
pluralSeparator?: string;Char to split plural from key '_'
property postProcess
postProcess?: false | string | readonly string[];String or array of postProcessors to apply per default false
property postProcessPassResolved
postProcessPassResolved?: boolean;passthrough the resolved object including 'usedNS', 'usedLang' etc into options object of postprocessors as 'i18nResolved' property false
property preload
preload?: false | readonly string[];Array of languages to preload. Important on server-side to assert translations are loaded before rendering views. false
property react
react?: ReactOptions;Options for react - check documentation of plugin undefined
property resources
resources?: Resource;Resources to initialize with (if not using loading or not appending using addResourceBundle) undefined
property retryTimeout
retryTimeout?: number;Set how long to wait, in milliseconds, between retries of failed requests. This number is compounded by a factor of 2 for subsequent retry. The default value is used if value is set below 1ms. 350
property returnDetails
returnDetails?: boolean;Returns an object that includes information about the used language, namespace, key and value false
property returnEmptyString
returnEmptyString?: boolean;Allows empty string as valid translation. Since v27 an empty string falls back like a missing value by default. false
property returnNull
returnNull?: boolean;Allows null values as valid translation false
property returnObjects
returnObjects?: boolean;Allows objects as valid translation result false
property saveMissing
saveMissing?: boolean;Calls the backend's
create()for keys that are not found, so new keys reach your translation files or service while you develop (keep it off in production).i18next-http-backendposts them to itsaddPath;i18next-locize-backend(https://www.locize.com/i18next?from=i18next_types__savemissing) sends them to Locize, the translation management service by the i18next maintainers, where they can be translated automatically. false
property saveMissingPlurals
saveMissingPlurals?: boolean;Calls save missing key function on backend if key not found also for plural forms. true
property saveMissingTo
saveMissingTo?: 'current' | 'all' | 'fallback';'fallback'
property supportedLngs
supportedLngs?: false | readonly string[];Array of allowed languages false
property updateMissing
updateMissing?: boolean;Experimental: enable to update default values using the saveMissing (Works only if defaultValue different from translated value. Only useful on initial development or when keeping code as source of truth not changing values outside of code. Only supported if backend supports it already) false
method overloadTranslationOptionHandler
overloadTranslationOptionHandler: (args: string[]) => TOptions;Sets defaultValue args => ({ defaultValue: args[1] })
method parseMissingKeyHandler
parseMissingKeyHandler: ( key: string, defaultValue?: string, options?: any) => any;Receives a key that was not found in
t()and returns a value, that will be returned byt()noop
method returnedObjectHandler
returnedObjectHandler: (key: string, value: string, options: any) => unknown;Gets called if object was passed in as key but returnObjects was set to false. What it returns is what
t()returns; without it,t()returns the key (since v27). noop
interface InterpolationOptions
interface InterpolationOptions {}property alwaysFormat
alwaysFormat?: boolean;Always format interpolated values. false
property defaultVariables
defaultVariables?: { [index: string]: any };Global variables to use in interpolation replacements undefined
property escapeValue
escapeValue?: boolean;Escape passed in values to avoid xss injection true
property formatSeparator
formatSeparator?: string;Used to separate format from interpolation value ','
property maxReplaces
maxReplaces?: number;After how many interpolation runs to break out before throwing a stack overflow 1000
property nestingOptionsSeparator
nestingOptionsSeparator?: string;Separates options from key ','
property nestingPrefix
nestingPrefix?: string;Prefix for nesting '$t('
property nestingSuffix
nestingSuffix?: string;Suffix for nesting ')'
property prefix
prefix?: string;Prefix for interpolation '{{'
property skipOnVariables
skipOnVariables?: boolean;If true, it will skip to interpolate the variables true
property suffix
suffix?: string;Suffix for interpolation '}}'
property unescapePrefix
unescapePrefix?: string;Prefix to unescaped mode '-'
property unescapeSuffix
unescapeSuffix?: string;Suffix to unescaped mode undefined
property useRawValueToEscape
useRawValueToEscape?: boolean;If true, then value passed into escape function is not casted to string, use with custom escape function that does its own type check false
method escape
escape: (str: string) => string;Escape function str => str
interface Interpolator
interface Interpolator {}method init
init: (options: InterpolationOptions, reset: boolean) => undefined;method interpolate
interpolate: ( str: string, data: object, lng: string, options: InterpolationOptions) => string;method nest
nest: ( str: string, fc: (...args: any[]) => any, options: InterpolationOptions) => string;method reset
reset: () => undefined;method resetRegExp
resetRegExp: () => undefined;interface LanguageDetectorAsyncModule
interface LanguageDetectorAsyncModule extends Module {}Used to detect language in user land. Can be provided as a singleton or as a prototype constructor (preferred for supporting multiple instances of i18next). For singleton set property
typeto'languageDetector'For a prototype constructor set static property.
property async
async: true;Set to true to enable async detection
property callbackApi
callbackApi?: boolean;Declares how the async
detectanswers (since v26.7.0; as an instance or static property):truefordetect(callback),falsefordetect()returning a promise. Left out, i18next guesses it from the number of parameters, which is deprecated.
property type
type: 'languageDetector';method cacheUserLanguage
cacheUserLanguage: (lng: string) => void | Promise<void>;method detect
detect: ( callback: (lng: string | readonly string[] | undefined) => void | undefined) => void | Promise<string | readonly string[] | undefined>;Must call callback passing detected language or return a Promise
method init
init: ( services: Services, detectorOptions: object, i18nextOptions: InitOptions) => void;interface LanguageDetectorModule
interface LanguageDetectorModule extends Module {}Used to detect language in user land. Can be provided as a singleton or as a prototype constructor (preferred for supporting multiple instances of i18next). For singleton set property
typeto'languageDetector'For a prototype constructor set static property.
property type
type: 'languageDetector';method cacheUserLanguage
cacheUserLanguage: (lng: string) => void;method detect
detect: () => string | readonly string[] | undefined;Must return detected language
method init
init: ( services: Services, detectorOptions: object, i18nextOptions: InitOptions) => void;interface LoggerModule
interface LoggerModule extends Module {}Override the built-in console logger. Do not need to be a prototype function.
interface Modules
interface Modules {}property backend
backend?: BackendModule;property external
external: ThirdPartyModule[];property formatter
formatter?: FormatterModule;property i18nFormat
i18nFormat?: I18nFormatModule;property languageDetector
languageDetector?: LanguageDetectorModule | LanguageDetectorAsyncModule;property logger
logger?: LoggerModule;interface Newable
interface Newable<T> {}construct signature
new (...args: any[]): T;interface NewableModule
interface NewableModule<T extends Module> extends Newable<T> {}property type
type: T['type'];interface PostProcessorModule
interface PostProcessorModule extends Module {}Used to extend or manipulate the translated values before returning them in
tfunction. Need to be a singleton object.
interface ReactOptions
interface ReactOptions {}The
reactoptions of react-i18next, which fills in this interface (since v27; before, i18next declared them). Without react-i18next in the program,reacttakes any object.
interface Resource
interface Resource {}index signature
[language: string]: ResourceLanguage;interface ResourceLanguage
interface ResourceLanguage {}index signature
[namespace: string]: ResourceKey;interface ResourceNamespaceMap
interface ResourceNamespaceMap {}Per-package namespace types for monorepos. Augment this in each package's
i18next.d.tsinstead ofCustomTypeOptions.resourceswhen several packages need their own namespaces — otherwise TypeScript reports TS2717 on merge.Works alongside the legacy
CustomTypeOptions.resourcesfield; both end up inTypeOptions['resources'].Scalar type options like
defaultNS,returnNull,enableSelector, etc., still belong onCustomTypeOptions— this interface is for namespace resource types only.Example 1
// packages/ui/i18next.d.tsdeclare module 'i18next' {interface ResourceNamespaceMap {'@repo/ui': typeof uiTranslations;}}See Also
https://github.com/i18next/i18next/issues/2409
interface SelectorFn
interface SelectorFn<Source, Target, Opts extends SelectorOptions<unknown>> {}Public for react-i18next's
Transtypes (since v26.7.0).
call signature
(translations: Select<Source, Opts['context']>): Target;interface SelectorOptions
interface SelectorOptions<Ns = Namespace> extends Omit<TOptionsBase, 'ns' | 'nsSeparator'>, $Dictionary {}property ns
ns?: Ns;interface Services
interface Services {}property backendConnector
backendConnector: any;property formatter
formatter?: Formatter;property i18nFormat
i18nFormat: any;property interpolator
interpolator: Interpolator;property languageDetector
languageDetector: any;property languageUtils
languageUtils: any;property logger
logger: any;property pluralResolver
pluralResolver: any;property resourceStore
resourceStore: ResourceStore;property utils
utils?: { hasLoadedNamespace: i18n['hasLoadedNamespace']; /** Reloads resources through the backend, as `i18next.reloadResources()` (since v26.7.0) */ reloadResources: i18n['reloadResources'];};Calls bound to the i18next instance, for plugins
interface TFunction
interface TFunction<Ns extends Namespace = DefaultNamespace, KPrefix = undefined> extends TFunctionSignature<Ns, KPrefix> {}interface TFunctionNonStrict
interface TFunctionNonStrict< Ns extends Namespace = DefaultNamespace, KPrefix = undefined> extends Branded<Ns> {}interface TFunctionSelector
interface TFunctionSelector<Ns extends Namespace, KPrefix, Source> extends Branded<Ns> {}interface TFunctionStrict
interface TFunctionStrict< Ns extends Namespace = DefaultNamespace, KPrefix = undefined> extends Branded<Ns> {}************************ T function declaration * ************************
interface ThirdPartyModule
interface ThirdPartyModule extends Module {}interface TOptionsBase
interface TOptionsBase {}property context
context?: unknown;Used for contexts (eg. male\female)
property count
count?: number;Count value used for plurals
property defaultValue
defaultValue?: unknown;Default value to return if a translation was not found
property fallbackLng
fallbackLng?: false | FallbackLng;Override language to lookup key if not found see fallbacks for details
property interpolation
interpolation?: InterpolationOptions;Override interpolation options
property joinArrays
joinArrays?: string;Char, eg. '\n' that arrays will be joined by (can be set globally too)
property keyPrefix
keyPrefix?: string | (($: any) => any);Optional keyPrefix that will be applied to the key before resolving. Accepts a string or a selector function (e.g.
$ => $.deeply.nested). Only supported on the TFunction returned by getFixedT().
property keySeparator
keySeparator?: false | string;Override char to separate keys
property lng
lng?: string;Override language to use
property lngs
lngs?: readonly string[];Override languages to use
property ns
ns?: Namespace;Override namespaces (string or array)
property nsSeparator
nsSeparator?: false | string;Override char to split namespace from key
property ordinal
ordinal?: boolean;Ordinal flag for ordinal plurals
property postProcess
postProcess?: string | readonly string[];String or array of postProcessors to apply see interval plurals as a sample
property replace
replace?: any;Object with vars for interpolation - or put them directly in options
property returnDetails
returnDetails?: boolean;Returns an object that includes information about the used language, namespace, key and value
property returnObjects
returnObjects?: boolean;Accessing an object not a translation string (can be set globally too)
property skipInterpolation
skipInterpolation?: boolean;Skip interpolation and nesting for this call (since v26.7.0 in the types)
Type Aliases
type AppendKeyPrefix
type AppendKeyPrefix<Key, KPrefix> = _NoStrictNullChecks extends true // see ParseKeysByKeyPrefix ? [KPrefix] extends [undefined] ? Key : _AppendKeyPrefix<Key, KPrefix> : _AppendKeyPrefix<Key, KPrefix>;type AppendNamespace
type AppendNamespace<Ns, Keys> = `${Ns & string}${_NsSeparator}${Keys & string}`;type ApplyKeyPrefix
type ApplyKeyPrefix< T extends [any], KPrefix> = KPrefix extends `${infer Head}${_KeyPrefixSeparator}${infer Tail}` ? ApplyKeyPrefix<[T[0][Head]], Tail> : T[0][KPrefix & string];type ApplyTarget
type ApplyTarget< Target, Opts extends { returnObjects?: unknown }> = Opts['returnObjects'] extends true ? unknown : Target;Public for react-i18next's
Transtypes (since v26.7.0).
type Callback
type Callback = (error: any, t: TFunction) => void;type CallbackError
type CallbackError = Error | string | null | undefined;type ConstrainTarget
type ConstrainTarget<Opts extends SelectorOptions<any>> = _ReturnObjects extends true ? unknown : Opts['returnObjects'] extends true ? unknown : $IsResourcesDefined extends false ? unknown : string;Public for react-i18next's
Transtypes (since v26.7.0).
type ContextOfKey
type ContextOfKey< Key extends string, Ns extends Namespace = DefaultNamespace, TOpt extends TOptions = {}, KPrefix = undefined, ActualNS extends Namespace = NsByTOptions<Ns, TOpt>, Objects = TOpt['returnObjects'] extends true ? true : _ReturnObjects> = $IsResourcesDefined extends true ? _OrScan< | _ContextIn< Resources[$FirstNamespace<ActualNS> & keyof Resources], AppendKeyPrefix<Key, KPrefix> & string, TOpt['context'], Objects > | (ActualNS extends readonly (infer NsList)[] ? Key extends `${infer N extends NsList & keyof Resources & string}${_NsSeparator}${infer Rest}` ? _ContextIn<Resources[N], Rest, TOpt['context'], Objects> : never : never) | _ContextIn< FallbackResourcesOf<_FallbackNamespace, Resources>, Key, TOpt['context'], Objects >, Key, Ns, TOpt, KPrefix > : string;The type of
contextfor a key:stringwhen the key also exists without a context, else the passed context values that have a key of their own (${key}${_ContextSeparator}${context}, plural forms included). The key is looked up along its path in the namespace it names (ns:, else the first namespace with the key prefix, and the fallback namespace): matched against the keys of all namespaces, every key cost the size of all resources.
type DeepUnwrapPlural
type DeepUnwrapPlural<T> = T extends PluralValue<infer U> ? U : T extends readonly any[] ? { [I in keyof T]: DeepUnwrapPlural<T[I]> } : T extends object ? { [K in keyof T]: DeepUnwrapPlural<T[K]> } : T;Recursively strips the PluralValue brand from a type (handles nested objects for
returnObjects).
type DefaultNamespace
type DefaultNamespace = TypeOptions['defaultNS'];type DefaultTReturn
type DefaultTReturn<TOpt extends { returnObjects?: unknown }> = | TReturnOptionalObjects<TOpt> | TReturnOptionalNull;type EffectiveKPrefix
type EffectiveKPrefix<KPrefix, TOpt> = TOpt extends { keyPrefix: infer OptKP extends string;} ? OptKP : KPrefix;Resolves the effective key prefix by preferring a per-call
keyPrefixfrom options over the interface-levelKPrefix(set via getFixedT's 3rd argument).
type FallbackLng
type FallbackLng = | string | readonly string[] | FallbackLngObjList | ((code: string) => string | readonly string[] | FallbackLngObjList);type FallbackResourcesOf
type FallbackResourcesOf<FallbackNS, R> = FallbackNS extends readonly (infer FN)[] ? R[FN & keyof R] : [FallbackNS] extends [false] ? never : R[Extract<FallbackNS, keyof R> & keyof R];type FilterKeys
type FilterKeys<T, Context> = T extends readonly any[] ? 0 extends 1 & T ? FilterKeysObject<T, Context> // `any` reaches both branches; keep one result : { [I in keyof T]: FilterKeys<T[I], Context> } : FilterKeysObject<T, Context>;Distributes FilterKeysObject over unions so heterogeneous JSON array element types (each object literal in the array) are filtered independently, then re-unified. Without distribution,
keyof (A | B)is only the common keys and context variants that exist on a single element are invisible, which produced partial element unions forreturnObjects+context(#2398).The array check itself must distribute too (
T extends, not[T] extends): comparing twoTFunctions over a generic namespace otherwise relates the array branch throughkeyof (readonly any[] & Source), whose constraint is the intersection of every namespace's keys, a cross product that fails with TS2590 once there are many wide namespaces.
type FilterKeysByContext
type FilterKeysByContext<Keys, Context> = _NoStrictNullChecks extends true // see ParseKeysByKeyPrefix ? [Context] extends [undefined] ? Keys : _FilterKeysByContext<Keys, Context> : _FilterKeysByContext<Keys, Context>;type FilterKeysObject
type FilterKeysObject<T, Context> = { // Mapped type 1: object-valued keys (recurse) + plain leaf keys (non-plural, non-context) [K in keyof T as [keyof T[K]] extends [never] ? never // nothing to select (empty object, null, undefined, optional or unknown) : T[K] extends object ? K : [Context] extends [string] ? K extends | `${string}${_ContextSeparator}${Context}` | `${string}${_ContextSeparator}${Context}${_PluralSeparator}${PluralSuffix}` ? never // context keys handled by mapped type 3 : K extends `${string}${_PluralSeparator}${PluralSuffix}` ? never // plural keys handled by mapped type 2 : K extends string ? _HasContextVariant<T, K, Context> extends true ? never // context variant exists, drop base key (type 3 handles it) : _IsContextualKey<T, K> extends true ? never // key has context variants but not for this context : K // no context variants at all, keep base key : K : K extends `${string}${_PluralSeparator}${PluralSuffix}` ? never : K]: T[K] extends object ? FilterKeys<T[K], Context> : T[K];} & { // Mapped type 2: plural collapsing (active regardless of context) [K in keyof T as T[K] extends object ? never : [Context] extends [string] ? K extends | `${string}${_ContextSeparator}${Context}` | `${string}${_ContextSeparator}${Context}${_PluralSeparator}${PluralSuffix}` ? never // context keys handled by mapped type 3 : K extends | `${infer Prefix}${_PluralSeparator}${PluralSuffix}` | `${infer Prefix}${_PluralSeparator}ordinal${_PluralSeparator}${PluralSuffix}` ? Prefix : never : K extends | `${infer Prefix}${_PluralSeparator}${PluralSuffix}` | `${infer Prefix}${_PluralSeparator}ordinal${_PluralSeparator}${PluralSuffix}` ? Prefix : never]: T[K] extends object ? FilterKeys<T[K], Context> : PluralValue<T[K] & string>;} & { // Mapped type 3: context key collapsing (skip JSON-union phantoms typed as `undefined`) [K in keyof T as T[K] extends object ? never : [keyof T[K]] extends [never] ? never : [Context] extends [string] ? K extends | `${infer Prefix}${_ContextSeparator}${Context}` | `${infer Prefix}${_ContextSeparator}${Context}${_PluralSeparator}${PluralSuffix}` ? Prefix : never : never]: T[K] extends object ? FilterKeys<T[K], Context> : T[K];};type FlatNamespace
type FlatNamespace = $PreservedValue<keyof TypeOptions['resources'], string>;type FormatFunction
type FormatFunction = ( value: any, format?: string, lng?: string, options?: InterpolationOptions & $Dictionary<any>) => string;type GetSource
type GetSource< Ns extends Namespace, KPrefix, Res = NsResource<Ns>> = KPrefix extends (...args: any[]) => any ? SelectorReturnSource<KPrefix, Res> : KPrefix extends keyof Res ? Res[KPrefix] : _NoKeyPrefix<KPrefix> extends true ? Res : ApplyKeyPrefix<[Res], KPrefix>;Public for react-i18next's
Transtypes (since v26.7.0).
type InterpolationMap
type InterpolationMap<Ret> = _WithDefaultVariables< [_ParseInterpolation] extends ['icu'] ? $PreservedValue<_IcuArgsMap<Ret>, Record<string, unknown>> : [_ParseInterpolation] extends ['mf2'] ? $PreservedValue<_Mf2ArgsMap<Ret>, Record<string, unknown>> : $PreservedValue< _InterpolationMapFromEntries<ParseInterpolationEntries<Ret>>, Record<string, unknown> >>;type JoinKeys
type JoinKeys<K1, K2> = `${K1 & string}${_KeySeparator}${K2 & string}`;type KeyFromSelectorFn
type KeyFromSelectorFn = < Ns extends Namespace = DefaultNamespace, KPrefix extends KeyPrefix<Ns> = undefined>( selector: (src: Select<GetSource<Ns, KPrefix>, undefined>) => any, opts?: { ns?: Ns; keyPrefix?: KPrefix }) => SelectorKey;Type-safe signature for keyFromSelector. Constrains the selector callback against the default namespace's resources (same source that
t()uses for selectors without explicitns). When resources are not defined, accepts any selector.
type KeyPrefix
type KeyPrefix<Ns extends Namespace> = | (TypeOptions['keySeparator'] extends false ? _DotPrefixes<ResourceKeys<true>[$FirstNamespace<Ns>]> : ResourceKeys<true>[$FirstNamespace<Ns>]) | undefined;type KeyPrefixSelector
type KeyPrefixSelector<Ns extends Namespace> = (src: NsResource<Ns>) => object;A selector function that can be used as
keyPrefixto scopet()to a sub-tree of the resource.
type KeysBuilder
type KeysBuilder<Res, WithReturnObjects> = $IsResourcesDefined extends true ? WithReturnObjects extends true ? keyof Res | KeysBuilderWithReturnObjects<Res> : KeysBuilderWithoutReturnObjects<Res> : string;type KeysBuilderWithoutReturnObjects
type KeysBuilderWithoutReturnObjects< Res, Key = keyof $OmitArrayKeys<Res>> = Key extends _KeysOf<Res> ? _IsBranch<Res[Key]> extends true ? JoinKeys<Key, KeysBuilderWithoutReturnObjects<Res[Key]>> : Key : never;type KeysBuilderWithReturnObjects
type KeysBuilderWithReturnObjects<Res, Key = keyof Res> = Key extends _KeysOf<Res> ? _IsBranch<Res[Key]> extends true ? | JoinKeys<Key, WithOrWithoutPlural<keyof $OmitArrayKeys<Res[Key]>>> | JoinKeys<Key, KeysBuilderWithReturnObjects<Res[Key]>> : never : never;**************************************************** Build all keys and key prefixes based on Resources * ****************************************************
type KeysByTOptions
type KeysByTOptions<TOpt extends TOptions> = TOpt['returnObjects'] extends true ? ResourceKeys<true> : ResourceKeys;********************************************************************** Parse t function keys based on the namespace, options and key prefix * **********************************************************************
type KeysWithoutReturnObjects
type KeysWithoutReturnObjects = { [Ns in FlatNamespace]: WithOrWithoutPlural<KeysBuilder<Resources[Ns], false>>;};type KeysWithReturnObjects
type KeysWithReturnObjects = { [Ns in FlatNamespace]: WithOrWithoutPlural<KeysBuilder<Resources[Ns], true>>;};type KeyWithContext
type KeyWithContext<Key, TOpt extends TOptions> = _NoStrictNullChecks extends true // see ParseKeysByKeyPrefix ? [TOpt['context']] extends [undefined] ? Key : _KeyWithContext<Key, TOpt['context']> : TOpt['context'] extends string ? `${Key & string}${_ContextSeparator}${TOpt['context']}` : Key;type ModuleType
type ModuleType = | 'backend' | 'logger' | 'languageDetector' | 'postProcessor' | 'i18nFormat' | 'formatter' | '3rdParty';type MultiReadCallback
type MultiReadCallback = ( err: CallbackError, data: Resource | null | undefined) => void;type Namespace
type Namespace<T = FlatNamespace> = T | readonly T[];type NsArg
type NsArg<Ns extends Namespace> = Ns[number] | readonly Ns[number][];type NsByTOptions
type NsByTOptions< Ns extends Namespace, TOpt extends TOptions> = TOpt['ns'] extends Namespace ? _NoStrictNullChecks extends true ? // without strictNullChecks an absent `ns` reads as the whole `Namespace` type Namespace extends TOpt['ns'] ? Ns : TOpt['ns'] : TOpt['ns'] : Ns;type NsResource
type NsResource<Ns extends Namespace> = [_EnableSelector] extends ['strict'] ? _NsResourceStrict<Ns> : Ns extends readonly [keyof Resources, any, ...any] ? Resources[Ns[0]] & PickNamespaces<Resources, Ns[number]> : Resources[$FirstNamespace<Ns>];The raw (unfiltered) resource object for a given namespace.
type ParseActualValue
type ParseActualValue<Ret> = Ret extends `${_UnescapePrefix}${infer ActualValue}${_UnescapeSuffix}` ? TrimSpaces<ActualValue> : Ret;******************************************************* Parse t function return type and interpolation values * *******************************************************
type ParseInterpolationEntries
type ParseInterpolationEntries<Ret> = [_ParseInterpolation] extends [ false | 'icu' | 'mf2'] ? never : Ret extends `${string}${_InterpolationPrefix}${infer Value}${_InterpolationSuffix}${infer Rest}` ? | (Value extends `${infer ActualValue}${_InterpolationFormatSeparator}${infer Format}` ? [ParseActualValue<ActualValue>, TrimSpaces<Format>] : [ParseActualValue<Value>, never]) | ParseInterpolationEntries<Rest> : never;Parses interpolation entries as
[variableName, formatSpecifier | never]tuples.
type ParseInterpolationValues
type ParseInterpolationValues<Ret> = ParseInterpolationEntries<Ret>[0];Extracts just the variable names (kept for backward compat with ParseInterpolationValues usage).
type ParseKeys
type ParseKeys< Ns extends Namespace = DefaultNamespace, TOpt extends TOptions = {}, KPrefix = undefined, Keys extends $Dictionary = KeysByTOptions<TOpt>, ActualNS extends Namespace = NsByTOptions<Ns, TOpt>, Context extends TOpt['context'] = TOpt['context']> = $IsResourcesDefined extends true ? FilterKeysByContext< | ParseKeysByKeyPrefix<Keys[$FirstNamespace<ActualNS>], KPrefix> | ParseKeysByNamespaces<ActualNS, Keys> | ParseKeysByFallbackNs<Keys>, Context > : string;type ParseKeysByFallbackNs
type ParseKeysByFallbackNs<Keys extends $Dictionary> = _FallbackNamespace extends false ? never : _FallbackNamespace extends (infer UnionFallbackNs extends string)[] ? Keys[UnionFallbackNs] : Keys[_FallbackNamespace & string];type ParseKeysByKeyPrefix
type ParseKeysByKeyPrefix<Keys, KPrefix> = _NoStrictNullChecks extends true ? [KPrefix] extends [undefined] ? Keys : _ParseKeysByKeyPrefix<Keys, KPrefix> : _ParseKeysByKeyPrefix<Keys, KPrefix>;type ParseKeysByNamespaces
type ParseKeysByNamespaces< Ns extends Namespace, Keys> = Ns extends readonly (infer UnionNsps)[] ? UnionNsps extends keyof Keys ? AppendNamespace<UnionNsps, Keys[UnionNsps]> : never : never;type ParseKeysWithoutVariables
type ParseKeysWithoutVariables< Ns extends Namespace = DefaultNamespace, KPrefix = undefined> = _KeysWithoutVariables<ParseKeys<Ns, {}, KPrefix>, Ns, KPrefix>;The keys of
ParseKeys<Ns, {}, KPrefix>thatt()takes without options: their string has no variables, and a plural key is left out when its forms takecount. For a wrapper that passes a key on tot(), which then compiles withstrictInterpolationChecks(since v26.7.0):Example 1
import type { ParseKeysWithoutVariables } from 'i18next';const label = (key: ParseKeysWithoutVariables<'common'>) => t(key);
type ParseTReturn
type ParseTReturn<Key, Res, TOpt extends TOptions = {}> = ParseTReturnWithFallback< Key, Key extends `${infer K1}${_KeySeparator}${infer RestKey}` ? ParseTReturn<RestKey, _ValueOf<Res, K1>, TOpt> : // Process plurals only if count is provided inside options TOpt['count'] extends number ? TOpt['ordinal'] extends boolean ? ParseTReturnPluralOrdinal<Res, Key> : ParseTReturnPlural<Res, Key> : // otherwise access plain key without adding plural and ordinal suffixes Res extends readonly unknown[] ? Key extends `${infer NKey extends number}` ? Res[NKey] : never : _ValueOf<Res, Key>>;type ParseTReturnPlural
type ParseTReturnPlural< Res, Key, KeyWithPlural = `${Key & string}${_PluralSeparator}${PluralSuffix}`> = _ValueOf<Res, KeyWithPlural | Key>;type ParseTReturnPluralOrdinal
type ParseTReturnPluralOrdinal< Res, Key, KeyWithOrdinalPlural = `${Key & string}${_PluralSeparator}ordinal${_PluralSeparator}${PluralSuffix}`> = _ValueOf<Res, KeyWithOrdinalPlural | Key>;type ParseTReturnWithFallback
type ParseTReturnWithFallback<Key, Val> = Val extends '' ? _ReturnEmptyString extends true ? '' : Key : Val extends null ? _ReturnNull extends true ? null : Key : Val;type PickNamespaces
type PickNamespaces<T, K extends keyof any> = { [P in K as P extends keyof T ? P : never]: T[P & keyof T];};type PluginOptions
type PluginOptions<T> = $MergeBy< { /** * Options for language detection - check documentation of plugin * @default undefined */ detection?: object;
/** * Options for backend - check documentation of plugin * @default undefined */ backend?: T;
/** * Options for cache layer - check documentation of plugin * @default undefined */ cache?: object;
/** * Options for i18n message format - check documentation of plugin * @default undefined */ i18nFormat?: object; }, CustomPluginOptions>;type PluralSuffix
type PluralSuffix = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other';type PluralValue
type PluralValue<T extends string> = T & { readonly [$PluralBrand]: typeof $PluralBrand;};Marks a value as coming from a plural-form key, requiring
countin the selector options.
type ProcessReturnValue
type ProcessReturnValue<Target, DefaultValue> = $Turtles extends Target ? string : [DefaultValue] extends [never] ? Target : unknown extends DefaultValue ? Target : Target | DefaultValue;type ReadCallback
type ReadCallback = ( err: CallbackError, data: ResourceKey | boolean | null | undefined) => void;type ResourceKey
type ResourceKey = | string | { [key: string]: any; };type ResourceKeys
type ResourceKeys<WithReturnObjects = _ReturnObjects> = WithReturnObjects extends true ? KeysWithReturnObjects : KeysWithoutReturnObjects;type Resources
type Resources = $ValueIfResourcesDefined<_Resources, $Dictionary<string>>;type Select
type Select<T, Context> = $IsResourcesDefined extends false ? $Turtles : [_EnableSelector] extends ['optimize'] ? T : FilterKeys<T, Context>;type SelectorKey
type SelectorKey = string & { readonly [$SelectorKeyBrand]: typeof $SelectorKeyBrand;};A branded string produced by keyFromSelector. Can be passed directly to
t()when the selector API is enabled.
type SelectorParam
type SelectorParam<Ns extends Namespace = DefaultNamespace, KPrefix = undefined> = ( src: Select<GetSource<Ns, KPrefix>, undefined>) => string;The type of a selector function accepted by
t()for a given namespace and optional key prefix. Use this instead ofParameters<TFunction<Ns>>[0]for a stable, readable type.Example 1
import type { SelectorParam } from 'i18next';interface CmpProps {i18nKey: SelectorParam<'myNamespace'>;}
type SelectorReturn
type SelectorReturn< Target, Opts extends { defaultValue?: unknown; returnObjects?: boolean }, DV = Opts['defaultValue']> = $IsResourcesDefined extends true ? TFunctionReturnOptionalDetails< ProcessReturnValue<DeepUnwrapPlural<Target>, DV>, Opts > : DefaultTReturn<Opts>;type SelectorReturnSource
type SelectorReturnSource<KPrefix, Fallback> = KPrefix extends ( ...args: any[]) => infer R ? R extends object ? R : Fallback : Fallback;Extracts the sub-tree returned by a selector function used as keyPrefix.
type TFunctionDetailedResult
type TFunctionDetailedResult<T = string, TOpt extends TOptions = {}> = { /** * The plain used key */ usedKey: string; /** * The translation result. */ res: T; /** * The key with context / plural */ exactUsedKey: string; /** * The used language for this translation. */ usedLng: string; /** * The used namespace for this translation. */ usedNS: string; /** * The parameters used for interpolation. */ usedParams: InterpolationMap<T> & { count?: TOpt['count'] };};type TFunctionProcessReturnValue
type TFunctionProcessReturnValue<Ret, DefaultValue> = Ret extends | string | $SpecialObject | null ? Ret : [DefaultValue] extends [never] ? Ret : DefaultValue;type TFunctionReturn
type TFunctionReturn< Ns extends Namespace, Key, TOpt extends TOptions, ActualNS extends Namespace = NsByTOptions<Ns, TOpt>, ActualKey = KeyWithContext<Key, TOpt>, // a key without a value, e.g. a plural key without `count` NotFound = DefaultTReturn<TOpt>> = $IsResourcesDefined extends true ? ActualKey extends `${infer Nsp}${_NsSeparator}${infer RestKey}` ? [ParseTReturn<RestKey, Resources[Nsp & keyof Resources], TOpt>] extends [ never ] ? NotFound : ParseTReturn<RestKey, Resources[Nsp & keyof Resources], TOpt> : $FirstNamespace<ActualNS> extends infer PrimaryNS ? [PrimaryNS] extends [keyof Resources] ? [_PrimaryParse<ActualKey, PrimaryNS & keyof Resources, TOpt>] extends [ never ] ? [_FallbackParse<ActualKey, _FallbackNamespace, TOpt>] extends [ never ] ? NotFound : _FallbackParse<ActualKey, _FallbackNamespace, TOpt> : _PrimaryParse<ActualKey, PrimaryNS & keyof Resources, TOpt> : never : never : DefaultTReturn<TOpt>;type TFunctionReturnOptionalDetails
type TFunctionReturnOptionalDetails< Ret, TOpt extends TOptions> = TOpt['returnDetails'] extends true ? TFunctionDetailedResult<Ret, TOpt> : Ret;type TFunctionSignature
type TFunctionSignature< Ns extends Namespace = DefaultNamespace, KPrefix = undefined> = _EnableSelector extends true | 'optimize' | 'strict' ? TFunctionSelector<Ns, KPrefix, GetSource<Ns, KPrefix>> : _StrictKeyChecks extends true ? TFunctionStrict<Ns, KPrefix> : TFunctionNonStrict<Ns, KPrefix>;type TOptions
type TOptions<TInterpolationMap extends object = $Dictionary> = TOptionsBase & TInterpolationMap;type TReturnOptionalNull
type TReturnOptionalNull = _ReturnNull extends true ? null : never;type TReturnOptionalObjects
type TReturnOptionalObjects<TOpt extends { returnObjects?: unknown }> = _ReturnObjects extends true ? $SpecialObject | string : TOpt['returnObjects'] extends true ? $SpecialObject : string;type TrimSpaces
type TrimSpaces< T extends string, Acc extends string = ''> = T extends `${infer Char}${infer Rest}` ? Char extends ' ' ? TrimSpaces<Rest, Acc> : TrimSpaces<Rest, `${Acc}${Char}`> : T extends '' ? Acc : never;type TypeOptions
type TypeOptions = $MergeBy< $MergeBy< { /** @see {InitOptions.returnNull} */ returnNull: false;
/** @see {InitOptions.returnEmptyString} */ returnEmptyString: false;
/** @see {InitOptions.returnObjects} */ returnObjects: false;
/** @see {InitOptions.keySeparator} */ keySeparator: '.';
/** @see {InitOptions.nsSeparator} */ nsSeparator: ':';
/** @see {InitOptions.pluralSeparator} */ pluralSeparator: '_';
/** @see {InitOptions.contextSeparator} */ contextSeparator: '_';
/** @see {InitOptions.defaultNS} */ defaultNS: 'translation';
/** @see {InitOptions.fallbackNS} */ fallbackNS: false;
/** @see {InitOptions.resources} */ resources: object;
/** * Flag that allows HTML elements to receive objects. This is only useful for React applications * where you pass objects to HTML elements so they can be replaced to their respective interpolation * values (mostly with Trans component) */ allowObjectInHTMLChildren: false;
/** * Flag that enables strict key checking even if a `defaultValue` has been provided. * This ensures all calls of `t` function don't accidentally use implicitly missing keys. */ strictKeyChecks: false;
/** * Flag that makes the `t()` options required for a string with interpolation * variables, so that `{{name}}` cannot be left out of a call. Applies to the * string-key API (with `strictKeyChecks`, also to `t(key, defaultValue)`) and * to the selector API. Messages under `parseInterpolation: 'icu'` or `'mf2'` * require their arguments regardless of this flag. * * On by default since v27; set it to `false` to keep the v26 types. * @default true */ strictInterpolationChecks: true;
/** * Prefix for interpolation */ interpolationPrefix: '{{';
/** * Suffix for interpolation */ interpolationSuffix: '}}';
/** * Separates the variable from its format, as in `{{price, currency}}` (since v26.7.0) * @see {InterpolationOptions.formatSeparator} */ interpolationFormatSeparator: ',';
/** @see {InterpolationOptions.unescapePrefix} */ unescapePrefix: '-';
/** @see {InterpolationOptions.unescapeSuffix} */ unescapeSuffix: '';
/** * Whether to extract interpolation variables from translation strings at * the type level. When `true` (default), the type system parses each * resource value for `{{variable}}` patterns and types the `t()` options * accordingly. * * Set to `false` when your translation strings use a different * interpolation syntax that the i18next type extractor cannot understand * — e.g. ICU MessageFormat plurals like `{count, plural, one {{count} row} * other {{count} rows}}` would otherwise produce phantom variable names * because the default extractor naively matches the outermost `{{` … * `}}`. This flag is type-only; runtime interpolation is governed by * `InterpolationOptions` and is unaffected. * * Set to `'icu'` with `i18next-icu` to type `t()` options from the ICU * MessageFormat arguments instead: `{name}` takes `string | number`, * `{n, number}`, `plural` and `selectordinal` take `number`, `{d, date}` * and `{t, time}` take `Date`, `select` takes its case keys or any string * (for `other`), and arguments nested in cases are required too. * `interpolationFormatTypeMap` overrides a type by its format name (e.g. * `date: Date | number`). Options become required for a message with * arguments. * * Set to `'mf2'` with `i18next-mf2` to type `t()` options from the * MessageFormat 2 variables: `{$name}` takes `string | number`, a * variable annotated with `:number`, `:integer`, `:currency`, `:percent` * or `:unit` (directly or through `.input`/`.local`) takes `number`, * `:datetime`, `:date` and `:time` take `Date`, `:string` takes `string`, * option and markup variables (`minimumFractionDigits=$digits`, * `{#link href=$url}`) take `string | number`, and `.local` variables are * not arguments. `interpolationFormatTypeMap` overrides a type by its * function name. * * @default true */ parseInterpolation: true;
/** * Use a proxy-based selector to select a translation. * * Enables features like go-to definition, and better DX/faster autocompletion * for TypeScript developers. * * If you're working with an especially large set of translations and aren't * using context, you set `enableSelector` to `"optimize"` and i18next won't do * any type-level processing of your translations at all. * * With `enableSelector` set to `"optimize"`, i18next is capable of supporting * arbitrarily large/deep translation sets without causing any IDE slowdown * whatsoever. * * Set `enableSelector` to `"strict"` to require an explicit namespace as the * first selector path segment in every call. The selector proxy stops * exposing the primary namespace's keys flat on `$` — even * `useTranslation('only')` must use `$.only.foo`, never `$.foo`. At runtime, * a leading segment matching the scope's namespace list (primary included) * is always rewritten as a namespace prefix, fully decoupling selector * shape from resolution scope. Use this when you want a single mental model * for selector paths regardless of how many namespaces a hook was created * with, and to remove the silent miss that flat-primary paths can otherwise * cause in multi-ns hooks (see [#2429](https://github.com/i18next/i18next/issues/2429)). * * `"strict"` mode is incompatible with the `"optimize"` shortcut. If you * have keys whose names match sibling namespaces (the * [#2405](https://github.com/i18next/i18next/issues/2405) pattern), do not * enable strict mode — the leading-segment rewrite would route those keys * into the wrong namespace. * * @default false */ enableSelector: false;
/** * Maps interpolation format specifiers to their expected value types. * * By default, i18next infers types from built-in formatter names: * - `number`, `currency` → `number` * - `datetime` → `Date` * - `relativetime` → `number` * - `list` → `readonly string[]` * - No format specifier → `string | number` (since i18next stringifies values at runtime) * * Use this option to add mappings for custom formatters or to override * the built-in defaults. * * @default {} (empty — built-in defaults apply) * * @example * ```ts * interface CustomTypeOptions { * interpolationFormatTypeMap: { * // custom formatter * uppercase: string; * // override built-in * currency: string; * }; * } * ``` */ interpolationFormatTypeMap: {};
/** * The variables `interpolation.defaultVariables` fills in at runtime (since v26.7.0). They * become optional in the `t()` options, also with `strictInterpolationChecks`. * * @default {} * * @example * ```ts * interface CustomTypeOptions { * defaultVariables: { appName: string }; * } * ``` */ defaultVariables: {}; }, CustomTypeOptions >, // HACK: apply merged resources *after* CustomTypeOptions so registry contributions // survive when CustomTypeOptions.resources is also defined. Without this // second step, the inner $MergeBy would replace the default `resources: object` // with CustomTypeOptions['resources'] alone, dropping the registry namespaces. { resources: _MergedResources }>;type WithOrWithoutPlural
type WithOrWithoutPlural<Key> = Key extends `${infer KeyWithoutOrdinalPlural}${_PluralSeparator}ordinal${_PluralSeparator}${PluralSuffix}` ? KeyWithoutOrdinalPlural | Key : Key extends `${infer KeyWithoutPlural}${_PluralSeparator}${PluralSuffix}` ? KeyWithoutPlural | Key : Key;Package Files (3)
Dependencies (0)
No dependencies.
Dev Dependencies (28)
- @arktype/attest
- @babel/core
- @babel/preset-env
- @babel/preset-react
- @rollup/plugin-babel
- @rollup/plugin-terser
- @types/node
- @typescript-eslint/eslint-plugin
- @typescript-eslint/parser
- @vitest/coverage-v8
- cpy-cli
- eslint
- gh-release
- husky
- i18next-browser-languagedetector
- i18next-fs-backend
- i18next-http-backend
- i18next-localstorage-cache
- i18next-sprintf-postprocessor
- lint-staged
- neostandard
- nise
- prettier
- rimraf
- rollup
- typescript
- typescript-eslint
- vitest
Peer Dependencies (1)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/i18next.
- Markdown[](https://www.jsdocs.io/package/i18next)
- HTML<a href="https://www.jsdocs.io/package/i18next"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 6790 ms. - Missing or incorrect documentation? Open an issue for this package.
