import type { $OmitArrayKeys, $PreservedValue, $Dictionary, $SpecialObject, $StringKeyPathToRecord, $NoInfer, $Turtles, } from './helpers.js'; import type { TypeOptions, Namespace, FlatNamespace, DefaultNamespace, TOptions, TOptionsBase, } from './options.js'; // Only the declarations marked `export` are public: without an export list, every declaration of a // .d.ts module counts as exported, and the `_` and `$` helpers below were importable. export {}; /** @todo consider to replace {} with Record */ // Type Options type _ReturnObjects = TypeOptions['returnObjects']; type _ReturnEmptyString = TypeOptions['returnEmptyString']; type _ReturnNull = TypeOptions['returnNull']; // `keySeparator: false`: flat keys only (a `false` here made `nestedfalsec` keys and split keys at the // text "false") type _KeySeparator = Exclude; // what getFixedT() joins a key prefix and a key with: '.' when keySeparator is false type _KeyPrefixSeparator = TypeOptions['keySeparator'] extends false ? '.' : TypeOptions['keySeparator']; // `nsSeparator: false`: no `ns:key` keys (a `false` here made `nsfalsekey` keys and split keys containing "false") type _NsSeparator = Exclude; type _PluralSeparator = TypeOptions['pluralSeparator']; type _ContextSeparator = TypeOptions['contextSeparator']; type _FallbackNamespace = TypeOptions['fallbackNS']; type _Resources = TypeOptions['resources']; type _InterpolationPrefix = TypeOptions['interpolationPrefix']; type _InterpolationSuffix = TypeOptions['interpolationSuffix']; type _InterpolationFormatSeparator = TypeOptions['interpolationFormatSeparator']; type _DefaultVariables = TypeOptions['defaultVariables']; type _UnescapePrefix = TypeOptions['unescapePrefix']; type _UnescapeSuffix = TypeOptions['unescapeSuffix']; type _StrictKeyChecks = TypeOptions['strictKeyChecks']; type _StrictInterpolationChecks = TypeOptions['strictInterpolationChecks']; type _EnableSelector = TypeOptions['enableSelector']; type _ParseInterpolation = TypeOptions['parseInterpolation']; type _InterpolationFormatTypeMap = TypeOptions['interpolationFormatTypeMap']; type $IsResourcesDefined = [keyof _Resources] extends [never] ? false : true; type $ValueIfResourcesDefined = $IsResourcesDefined extends true ? Value : Fallback; type $FirstNamespace = Ns extends readonly any[] ? Ns[0] : Ns; export type Resources = $ValueIfResourcesDefined<_Resources, $Dictionary>; export type PluralSuffix = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other'; export type WithOrWithoutPlural = Key extends `${infer KeyWithoutOrdinalPlural}${_PluralSeparator}ordinal${_PluralSeparator}${PluralSuffix}` ? KeyWithoutOrdinalPlural | Key : Key extends `${infer KeyWithoutPlural}${_PluralSeparator}${PluralSuffix}` ? KeyWithoutPlural | Key : Key; export type JoinKeys = `${K1 & string}${_KeySeparator}${K2 & string}`; export type AppendNamespace = `${Ns & string}${_NsSeparator}${Keys & string}`; export type TrimSpaces< T extends string, Acc extends string = '', > = T extends `${infer Char}${infer Rest}` ? Char extends ' ' ? TrimSpaces : TrimSpaces : T extends '' ? Acc : never; export interface Branded { $TFunctionBrand: $IsResourcesDefined extends true ? `${Ns extends readonly any[] ? Ns[0] : Ns}` : never; } /** * `keyof Res`, built once per resource object. TypeScript does not cache * `keyof` of an object type, so `keyof Res` inside a conditional that runs per * key (or per `t()` call) rebuilt the union of all keys every time: quadratic * in the namespace size. Conditional type instantiations are cached. */ type _KeysOf = [Res] extends [unknown] ? keyof Res : never; /** * `Res[Key & keyof Res]`: a literal key is looked up directly instead of being * intersected with every key; a wide key (`string`, `${string}_suffix` from a * string context) still matches all keys it covers. */ type _ValueOf = Key extends _KeysOf ? Res[Key] : _IsLiteral extends true ? never : Res[Key & _KeysOf]; /** **************************************************** * Build all keys and key prefixes based on Resources * ***************************************************** */ // Do NOT add a `[Res] extends [never]` guard here: it defers these into // conditional types, so `KeyPrefix` no longer resolves to a literal union // and `keyPrefix` inference widens to the whole namespace, polluting `t()` // return types with sibling keys (#2434 regression). Guard `never` in the merge. export type KeysBuilderWithReturnObjects = Key extends _KeysOf ? Res[Key] extends $Dictionary | readonly unknown[] ? | JoinKeys>> | JoinKeys> : never : never; export type KeysBuilderWithoutReturnObjects> = Key extends _KeysOf ? Res[Key] extends $Dictionary | readonly unknown[] ? JoinKeys> : Key : never; export type KeysBuilder = $IsResourcesDefined extends true ? WithReturnObjects extends true ? keyof Res | KeysBuilderWithReturnObjects : KeysBuilderWithoutReturnObjects : string; export type KeysWithReturnObjects = { [Ns in FlatNamespace]: WithOrWithoutPlural>; }; export type KeysWithoutReturnObjects = { [Ns in FlatNamespace]: WithOrWithoutPlural>; }; export type ResourceKeys = WithReturnObjects extends true ? KeysWithReturnObjects : KeysWithoutReturnObjects; /** ********************************************************************** * Parse t function keys based on the namespace, options and key prefix * *********************************************************************** */ export type KeysByTOptions = TOpt['returnObjects'] extends true ? ResourceKeys : ResourceKeys; export type NsByTOptions = TOpt['ns'] extends Namespace ? TOpt['ns'] : Ns; export type ParseKeysByKeyPrefix = KPrefix extends string ? Keys extends `${KPrefix}${_KeyPrefixSeparator}${infer Key}` ? Key : never : Keys; export type ParseKeysByNamespaces< Ns extends Namespace, Keys, > = Ns extends readonly (infer UnionNsps)[] ? UnionNsps extends keyof Keys ? AppendNamespace : never : never; export type ParseKeysByFallbackNs = _FallbackNamespace extends false ? never : _FallbackNamespace extends (infer UnionFallbackNs extends string)[] ? Keys[UnionFallbackNs] : Keys[_FallbackNamespace & string]; export type FilterKeysByContext = Context extends string ? Keys extends | `${infer Prefix}${_ContextSeparator}${Context}${_PluralSeparator}${PluralSuffix}` | `${infer Prefix}${_ContextSeparator}${Context}` ? Prefix : never : Keys; export type ParseKeys< Ns extends Namespace = DefaultNamespace, TOpt extends TOptions = {}, KPrefix = undefined, Keys extends $Dictionary = KeysByTOptions, ActualNS extends Namespace = NsByTOptions, Context extends TOpt['context'] = TOpt['context'], > = $IsResourcesDefined extends true ? FilterKeysByContext< | ParseKeysByKeyPrefix], KPrefix> | ParseKeysByNamespaces | ParseKeysByFallbackNs, Context > : string; /** ******************************************************* * Parse t function return type and interpolation values * ******************************************************** */ export type ParseActualValue = Ret extends `${_UnescapePrefix}${infer ActualValue}${_UnescapeSuffix}` ? TrimSpaces : Ret; /** Parses interpolation entries as `[variableName, formatSpecifier | never]` tuples. */ export type ParseInterpolationEntries = [_ParseInterpolation] extends [false | 'icu' | 'mf2'] ? never : Ret extends `${string}${_InterpolationPrefix}${infer Value}${_InterpolationSuffix}${infer Rest}` ? | (Value extends `${infer ActualValue}${_InterpolationFormatSeparator}${infer Format}` ? [ParseActualValue, TrimSpaces] : [ParseActualValue, never]) | ParseInterpolationEntries : never; /** Extracts just the variable names (kept for backward compat with ParseInterpolationValues usage). */ export type ParseInterpolationValues = ParseInterpolationEntries[0]; /** Built-in i18next formatter name → value type mapping. */ type _BuiltInFormatTypeMap = { number: number; currency: number; datetime: Date; relativetime: number; list: readonly string[]; }; /** Strips inline formatting options, e.g. `currency(EUR)` → `currency`. */ type _StripFormatOptions = F extends `${infer Name}(${string})` ? Name : F; /** Resolves the type for a single interpolation entry based on name and format. */ type _ResolveEntryType = [Format] extends [never] ? Name extends 'count' ? number : string | number : Format extends keyof _InterpolationFormatTypeMap ? _InterpolationFormatTypeMap[Format] : _StripFormatOptions extends keyof _InterpolationFormatTypeMap ? _InterpolationFormatTypeMap[_StripFormatOptions & keyof _InterpolationFormatTypeMap] : Format extends keyof _BuiltInFormatTypeMap ? _BuiltInFormatTypeMap[Format] : _StripFormatOptions extends keyof _BuiltInFormatTypeMap ? _BuiltInFormatTypeMap[_StripFormatOptions & keyof _BuiltInFormatTypeMap] : string; /** Local union-to-intersection (not exported from helpers). */ type _UnionToIntersection = (T extends unknown ? (k: T) => void : never) extends ( k: infer I, ) => void ? I : never; /** Builds a per-entry typed record from parsed interpolation entries and intersects them. */ type _InterpolationMapFromEntries = _UnionToIntersection< E extends [infer Name extends string, infer Format] ? $StringKeyPathToRecord> : never >; /** ********************************************************************* * ICU MessageFormat arguments (`parseInterpolation: 'icu'`) * *********************************************************************** */ type _IcuWhitespace = ' ' | '\n' | '\t' | '\r'; type _IcuTrim = S extends `${_IcuWhitespace}${infer R}` ? _IcuTrim : S extends `${infer R}${_IcuWhitespace}` ? _IcuTrim : S; /** * Drops ICU apostrophe quoting as intl-messageformat (i18next-icu) reads it: * `''` is a literal apostrophe, `'{...}'` (also `'}'`, `'<'`, `'>'`, `'#'`) is * literal text up to the next single apostrophe. * Simplification: `'#` quotes everywhere here, at runtime only inside plurals. */ type _IcuStripQuotes = S extends `${infer L}'${infer R}` ? R extends `'${infer R2}` ? _IcuStripQuotes : R extends `${'{' | '}' | '<' | '>' | '#'}${string}` ? _IcuStripQuotes<_IcuSkipQuoted, `${Acc}${L}`> : _IcuStripQuotes : `${Acc}${S & string}`; type _IcuSkipQuoted = S extends `${string}'${infer R}` ? R extends `'${infer R2}` ? _IcuSkipQuoted : R : ''; /** Reads up to the `}` closing an already opened `{`; returns `[content, rest]`. */ type _IcuBlock< S, Acc extends string = '', Depth extends 0[] = [], > = S extends `${infer L}}${infer R}` ? L extends `${infer L2}{${infer R2}` ? _IcuBlock<`${R2}}${R}`, `${Acc}${L2}{`, [...Depth, 0]> : Depth extends [0, ...infer D extends 0[]] ? _IcuBlock : [`${Acc}${L}`, R] : never; /** `[name, type]` entries of every argument in a message, nested cases included. */ type _IcuEntries = S extends `${string}{${infer R}` ? _IcuBlock extends [infer Arg, infer Rest] ? _IcuEntries> : Acc : Acc; /** Walks plural/select cases: `[selector keys, entries of all case messages]`. */ type _IcuCases = S extends `${infer L}{${infer R}` ? _IcuBlock extends [infer Msg, infer Rest] ? _IcuCases, Acc | _IcuEntries> : [Keys, Acc] : [Keys, Acc]; type _IcuArg = A extends `${infer Name},${infer Type},${infer Cases}` ? _IcuTrim extends 'plural' | 'selectordinal' ? [_IcuTrim, _IcuFormatType<_IcuTrim>] | _IcuCases[1] : _IcuTrim extends 'select' ? _IcuCases extends [infer Keys, infer E] ? [_IcuTrim, 'other' extends Keys ? Exclude | (string & {}) : Keys] | E : never : [_IcuTrim, _IcuFormatType<_IcuTrim>] // `{n, number, ::currency/EUR}` : A extends `${infer Name},${infer Type}` ? [_IcuTrim, _IcuFormatType<_IcuTrim>] : [_IcuTrim, _IcuFormatType]; /** `interpolationFormatTypeMap` wins, then ICU's built-in argument types. */ type _IcuFormatType = [F] extends [never] ? string | number : F extends keyof _InterpolationFormatTypeMap ? _InterpolationFormatTypeMap[F] : F extends 'number' | 'plural' | 'selectordinal' ? number : F extends 'date' | 'time' ? Date : string | number; /** * Merges `[name, type]` entries into one record: a name used twice gets both * types, a dotted MF2 name (`$user.name`) becomes a nested object. */ type _ArgsFromEntries = _UnionToIntersection< E extends [infer Name extends string, infer Type] ? Name extends `${string}.${string}` ? $StringKeyPathToRecord : { [K in Name]: Type } : never > extends infer M ? [E] extends [never] ? never : { [K in keyof M]: M[K] } : never; type _IcuArgsMap = Ret extends string ? string extends Ret ? never : _ArgsFromEntries<_IcuEntries<_IcuStripQuotes>> : never; /** ********************************************************************* * MessageFormat 2 variables (`parseInterpolation: 'mf2'`) * *********************************************************************** */ /** Drops `\`-escapes (`\{`, `\}`, `\|`, `\\`), so they are neither braces nor quotes. */ type _Mf2StripEscapes = S extends `${infer L}\\${string}${infer R}` ? _Mf2StripEscapes : `${Acc}${S & string}`; /** Reads an expression up to its `}`, skipping `|quoted literals|`; returns `[body, rest]`. */ type _Mf2Expression = S extends `${infer B}}${infer Rest}` ? B extends `${infer Before}|${infer Lit}` ? `${Lit}}${Rest}` extends `${string}|${infer After}` ? _Mf2Expression : never : [`${Acc}${B}`, Rest] : never; /** `[name, type]` entries of every variable in a message's expressions; `{{` opens a quoted pattern. */ type _Mf2Entries = S extends `${string}{${infer R}` ? R extends `{${infer Pattern}` ? _Mf2Entries : _Mf2Expression extends [infer Body, infer Rest] ? _Mf2Entries>> : Acc : Acc; type _Mf2Space = S extends `${infer L}${C}${infer R}` ? _Mf2Space<`${L} ${R}`, C> : S; type _Mf2Spaces = _IcuTrim<_Mf2Space<_Mf2Space<_Mf2Space, '\t'>, '\r'>>; type _Mf2Name = S extends `${infer N} ${string}` ? _Mf2Name : S extends `${infer N}/${string}` ? N : S; /** `{$x :fn opt=$y}`: `$x` typed by its function, option and markup variables `string | number`. */ type _Mf2ExprEntries = Body extends `$${infer R}` ? R extends `${infer Name} ${infer Tail}` ? | [Name, _Mf2FunctionType<_IcuTrim extends `:${infer F}` ? _Mf2Name : never>] | _Mf2Vars : [_Mf2Name, _Mf2FunctionType] : _Mf2Vars; /** Every `$name` in a string, typed `string | number`. */ type _Mf2Vars = S extends `${string}$${infer R}` ? _Mf2Vars, string | number]> : Acc; /** `interpolationFormatTypeMap` wins, then messageformat's built-in functions. */ type _Mf2FunctionType = [F] extends [never] ? string | number : F extends keyof _InterpolationFormatTypeMap ? _InterpolationFormatTypeMap[F] : F extends 'number' | 'integer' | 'currency' | 'percent' | 'offset' | 'unit' | 'math' ? number : F extends 'datetime' | 'date' | 'time' ? Date : F extends 'string' ? string : string | number; /** Names declared by `.local $name = ...` (local, not passed in). */ type _Mf2Locals = S extends `${string}.local${infer R}` ? _Mf2Locals extends `$${infer N}=${string}` ? _IcuTrim : never)> : Acc; /** `.match $a $b`: selectors, normally also declared by `.input` or `.local`. */ type _Mf2Selectors = S extends `${string}.match${infer R}` ? _Mf2Vars<_Mf2Spaces> : never; type _Mf2ArgsMap = Ret extends string ? string extends Ret ? never : _Mf2StripEscapes extends infer S ? _ArgsFromEntries< Exclude< _Mf2Entries | _Mf2Selectors, [_IcuTrim extends `.${string}` ? _Mf2Locals : never, unknown] > > : never : never; /** The variables declared in `defaultVariables` are optional: they are filled in at runtime. */ type _WithDefaultVariables = [keyof _DefaultVariables] extends [never] ? Map : Omit & Partial>; export type InterpolationMap = _WithDefaultVariables< [_ParseInterpolation] extends ['icu'] ? $PreservedValue<_IcuArgsMap, Record> : [_ParseInterpolation] extends ['mf2'] ? $PreservedValue<_Mf2ArgsMap, Record> : $PreservedValue< _InterpolationMapFromEntries>, Record > >; export type ParseTReturnPlural< Res, Key, KeyWithPlural = `${Key & string}${_PluralSeparator}${PluralSuffix}`, > = _ValueOf; export type ParseTReturnPluralOrdinal< Res, Key, KeyWithOrdinalPlural = `${Key & string}${_PluralSeparator}ordinal${_PluralSeparator}${PluralSuffix}`, > = _ValueOf; export type ParseTReturnWithFallback = Val extends '' ? _ReturnEmptyString extends true ? '' : Key : Val extends null ? _ReturnNull extends true ? null : Key : Val; export type ParseTReturn = ParseTReturnWithFallback< Key, Key extends `${infer K1}${_KeySeparator}${infer RestKey}` ? ParseTReturn, TOpt> : // Process plurals only if count is provided inside options TOpt['count'] extends number ? TOpt['ordinal'] extends boolean ? ParseTReturnPluralOrdinal : ParseTReturnPlural : // otherwise access plain key without adding plural and ordinal suffixes Res extends readonly unknown[] ? Key extends `${infer NKey extends number}` ? Res[NKey] : never : _ValueOf >; export type TReturnOptionalNull = _ReturnNull extends true ? null : never; export type TReturnOptionalObjects = _ReturnObjects extends true ? $SpecialObject | string : TOpt['returnObjects'] extends true ? $SpecialObject : string; export type DefaultTReturn = TReturnOptionalObjects | TReturnOptionalNull; export type KeyWithContext = TOpt['context'] extends string ? `${Key & string}${_ContextSeparator}${TOpt['context']}` : Key; export type ContextOfKey< Key extends string, Ns extends Namespace = DefaultNamespace, TOpt extends TOptions = {}, KPrefix = undefined, Keys extends $Dictionary = KeysByTOptions, ActualNS extends Namespace = NsByTOptions, ActualKeys = | ParseKeysByKeyPrefix], KPrefix> | ParseKeysByNamespaces | ParseKeysByFallbackNs, > = $IsResourcesDefined extends true ? Key extends ActualKeys ? string : ActualKeys extends | `${Key}${_ContextSeparator}${infer Context}${_PluralSeparator}${PluralSuffix}` | `${Key}${_ContextSeparator}${infer Context}` ? Context : never : string; // helper that maps the configured fallbackNS value to the matching resources slice export type FallbackResourcesOf = FallbackNS extends readonly (infer FN)[] ? R[FN & keyof R] : [FallbackNS] extends [false] ? never : R[Extract & keyof R]; /* reuse the parse helpers as top-level aliases (no nested type declarations) */ type _PrimaryParse< ActualKey, PrimaryNS extends keyof Resources, TOpt extends TOptions, > = ParseTReturn; type _FallbackParse = [ FallbackResourcesOf, ] extends [never] ? never : ParseTReturn, TOpt>; export type TFunctionReturn< Ns extends Namespace, Key, TOpt extends TOptions, ActualNS extends Namespace = NsByTOptions, ActualKey = KeyWithContext, // a key without a value, e.g. a plural key without `count` NotFound = DefaultTReturn, > = $IsResourcesDefined extends true ? ActualKey extends `${infer Nsp}${_NsSeparator}${infer RestKey}` ? [ParseTReturn] extends [never] ? NotFound : ParseTReturn : $FirstNamespace extends infer PrimaryNS ? [PrimaryNS] extends [keyof Resources] ? [_PrimaryParse] extends [never] ? [_FallbackParse] extends [never] ? NotFound : _FallbackParse : _PrimaryParse : never : never : DefaultTReturn; export type TFunctionDetailedResult = { /** * 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 & { count?: TOpt['count'] }; }; export type TFunctionProcessReturnValue = Ret extends string | $SpecialObject | null ? Ret : [DefaultValue] extends [never] ? Ret : DefaultValue; export type TFunctionReturnOptionalDetails< Ret, TOpt extends TOptions, > = TOpt['returnDetails'] extends true ? TFunctionDetailedResult : Ret; export type AppendKeyPrefix = KPrefix extends string ? `${KPrefix}${_KeyPrefixSeparator}${Key & string}` : Key; /** * Resolves the effective key prefix by preferring a per-call `keyPrefix` from * options over the interface-level `KPrefix` (set via getFixedT's 3rd argument). */ export type EffectiveKPrefix = TOpt extends { keyPrefix: infer OptKP extends string } ? OptKP : KPrefix; /** `parseInterpolation: 'icu'` or `'mf2'`: messages are typed by their arguments. */ type _ParsesMessageFormat = [_ParseInterpolation] extends ['icu'] | ['mf2'] ? true : false; /** * Whether `t()` options are required for a message with variables: always under * ICU / MF2 (on a missing one, i18next-icu renders the raw message and * i18next-mf2 a `{$name}` fallback), and with `strictInterpolationChecks: true` * for `{{variables}}` (i18next renders the raw placeholder). */ type _RequiresMessageOptions = _ParsesMessageFormat extends true ? true : [_ParseInterpolation] extends [true] ? _StrictInterpolationChecks extends true ? true : false : false; /** * `t()` options are optional, except for a message with variables when * `_RequiresMessageOptions` is true. The conditional resolves eagerly; a generic * one here would break inference. */ type _KeyAndOptions = _RequiresMessageOptions extends true ? [key: Key | Key[], options: Opts] | [key: (Key | Key[]) & _IfOptionalOptions] : [key: Key | Key[], options?: Opts]; /** * `t(key, defaultValue)` under `strictKeyChecks`: the variables are required only * with `strictInterpolationChecks`, else `unknown` (the call stays as before). */ type _IfOptionalDefaultOptions = _StrictInterpolationChecks extends true ? _IfOptionalOptions : unknown; /** `unknown` when options may be left out, else a type naming the missing arguments. */ type _IfOptionalOptions = _RequiresMessageOptions extends true ? {} extends InterpolationMap ? unknown : { 'pass these arguments as t() options': InterpolationMap } : unknown; /** * What a call without options is checked against: `Ret`, unless a key without a * value of its own (a plural key without `count`) widened it to `string`, which * hid the variables of every other key in a union. Only with * `strictInterpolationChecks`: without it (ICU and MF2 check their arguments * regardless of the flag) the types are the v26 ones. */ type _CheckedReturn< Ret, Ns extends Namespace, Key, TOpt extends TOptions, > = _StrictInterpolationChecks extends true ? string extends Ret ? _CheckedValue : Ret : Ret; /** * Per key: its value, or the plural forms of a key without one; `never` (not * `string`) for a key without either. The first lookup is the one `Ret` made * (cached), so only a key without a value is looked up again. */ type _CheckedValue = Key extends unknown ? TFunctionReturn< Ns, Key, TOpt, NsByTOptions, KeyWithContext, never > extends infer V ? [V] extends [never] ? _ValueWithCount, KeyWithContext> : V : never : never; /** The plural forms of a key, ordinal ones too, `never` for a key without them. */ type _ValueWithCount< Ns extends Namespace, Key, K = Key | `${Key & string}${_PluralSeparator}ordinal`, > = TFunctionReturn; /** * The variables a call with options must pass. With `strictInterpolationChecks` * those of `_CheckedReturn`, so a plural key without `count` needs the variables * of its forms, `count` included; without the flag those of `Ret`, as in v26. */ type _OptionsMap< Ret, Ns extends Namespace, Key, TOpt extends TOptions, > = _StrictInterpolationChecks extends true ? InterpolationMap<$NoInfer<_CheckedReturn>> : InterpolationMap; /** Options parameter of a selector overload: required for a message with arguments. */ type _SelectorOptionsArg = unknown extends _IfOptionalOptions ? [options?: Opts] : [options: Opts]; /** Union of the values an array of selectors resolves to (plural brands kept). */ type _SelectorsReturn = Fns[number] extends ( ...args: any[] ) => infer R ? R : never; /** Whether any member of the union is a plural group (`false` for `any`). */ type _HasPlural = 0 extends 1 & R ? false : [Extract>] extends [never] ? false : true; /** `{ count: number }` when any member of the union is a plural group. */ type _CountIfPlural = _HasPlural extends true ? { count: number } : {}; /** Options of a selector-array overload: required for variables or a plural member. */ type _SelectorArrayOptionsArg = _HasPlural extends true ? [options: Opts & { count: number } & InterpolationMap>] : _SelectorOptionsArg, Opts & InterpolationMap>>; /** ************************ * T function declaration * ************************* */ export interface TFunctionStrict< Ns extends Namespace = DefaultNamespace, KPrefix = undefined, > extends Branded { < const Key extends ParseKeys> | TemplateStringsArray, const TOpt extends TOptions, Ret extends TFunctionReturn>, TOpt>, >( key: Key | Key[], options: TOpt & _OptionsMap>, TOpt> & { context?: Key extends string ? unknown extends TOpt['context'] ? TOpt['context'] : ContextOfKey> : never; }, ): TFunctionReturnOptionalDetails, never>, TOpt>; < const Key extends ParseKeys> | TemplateStringsArray, const TOpt extends TOptions, Ret extends TFunctionReturn>, TOpt>, >( key: (Key | Key[]) & _IfOptionalOptions< $NoInfer< _CheckedReturn>, TOpt> > >, ): TFunctionReturnOptionalDetails, never>, TOpt>; < const Key extends ParseKeys> | TemplateStringsArray, const TOpt extends TOptions, Ret extends TFunctionReturn>, TOpt>, >( key: Key | Key[], defaultValue: string, options: TOpt & _OptionsMap>, TOpt> & { context?: Key extends string ? unknown extends TOpt['context'] ? TOpt['context'] : ContextOfKey> : never; }, ): TFunctionReturnOptionalDetails, never>, TOpt>; < const Key extends ParseKeys> | TemplateStringsArray, const TOpt extends TOptions, Ret extends TFunctionReturn>, TOpt>, >( key: (Key | Key[]) & _IfOptionalDefaultOptions< $NoInfer< _CheckedReturn>, TOpt> > >, defaultValue: string, ): TFunctionReturnOptionalDetails, never>, TOpt>; } export interface TFunctionNonStrict< Ns extends Namespace = DefaultNamespace, KPrefix = undefined, > extends Branded { < const Key extends ParseKeys> | TemplateStringsArray, const TOpt extends TOptions, Ret extends TFunctionReturn>, TOpt>, const ActualOptions extends Omit & _OptionsMap>, TOpt> & { context?: Key extends string ? unknown extends TOpt['context'] ? TOpt['context'] : ContextOfKey> : never; } = TOpt & _OptionsMap>, TOpt> & { context?: Key extends string ? unknown extends TOpt['context'] ? TOpt['context'] : ContextOfKey> : never; }, DefaultValue extends string = never, >( // `[key, defaultValue, options?]` is written as two tuples: on a failed call, // TypeScript elaborates the error against the last of the equally matching // members, and TypeScript 7 sorts a 3-element tuple last, so a wrong options // object was reported as "not assignable to type 'string'" instead of the // missing or mistyped argument. ...args: | [key: string | string[], options: TOpt & $Dictionary & { defaultValue: DefaultValue }] | [key: string | string[], defaultValue: DefaultValue] | [key: string | string[], defaultValue: DefaultValue, options: TOpt & $Dictionary] | _KeyAndOptions< Key, $NoInfer< _CheckedReturn>, TOpt> >, ActualOptions > ): TFunctionReturnOptionalDetails, DefaultValue>, TOpt>; } export type TFunctionSignature< Ns extends Namespace = DefaultNamespace, KPrefix = undefined, > = _EnableSelector extends true | 'optimize' | 'strict' ? TFunctionSelector> : _StrictKeyChecks extends true ? TFunctionStrict : TFunctionNonStrict; export interface TFunction< Ns extends Namespace = DefaultNamespace, KPrefix = undefined, > extends TFunctionSignature {} export type KeyPrefix = | (TypeOptions['keySeparator'] extends false ? _DotPrefixes[$FirstNamespace]> : ResourceKeys[$FirstNamespace]) | undefined; /** * With `keySeparator: false` a key prefix is joined with `.` and the result is looked up as a flat * key, so the prefixes are the parts of the flat keys before a `.`: `'a'` and `'a.b'` for `'a.b.c'`. */ type _DotPrefixes = string extends Keys ? string : _DotPrefixesOf; type _DotPrefixesOf = Key extends `${infer Head}.${infer Tail}` ? Head | `${Head}.${_DotPrefixesOf}` : never; /** * The keys of `ParseKeys` that `t()` takes without options: their string has no * variables, and a plural key is left out when its forms take `count`. For a wrapper that passes a * key on to `t()`, which then compiles with `strictInterpolationChecks` (since v26.7.0): * * @example * ```ts * import type { ParseKeysWithoutVariables } from 'i18next'; * * const label = (key: ParseKeysWithoutVariables<'common'>) => t(key); * ``` */ export type ParseKeysWithoutVariables< Ns extends Namespace = DefaultNamespace, KPrefix = undefined, > = _KeysWithoutVariables, Ns, KPrefix>; // a plural key without a value of its own is checked against its plural forms type _KeysWithoutVariables = Key extends string ? {} extends InterpolationMap<_CheckedValue, {}>> ? Key : never : never; /** * Strict variant: every namespace (primary included) is exposed under its own * key on `$`. The flattened-primary form (`Resources[Ns[0]] &`) is dropped, so * `$.foo` no longer typechecks when `foo` is a key in the primary namespace — * callers must write `$.primary.foo`. Applied uniformly to single- and * multi-ns hooks under `enableSelector: 'strict'`. */ type _NsResourceStrict = Ns extends readonly any[] ? PickNamespaces : PickNamespaces; /** The raw (unfiltered) resource object for a given namespace. */ export type NsResource = [_EnableSelector] extends ['strict'] ? _NsResourceStrict : Ns extends readonly [keyof Resources, any, ...any] ? Resources[Ns[0]] & PickNamespaces : Resources[$FirstNamespace]; /** A selector function that can be used as `keyPrefix` to scope `t()` to a sub-tree of the resource. */ export type KeyPrefixSelector = (src: NsResource) => object; /** * The type of a selector function accepted by `t()` for a given namespace and optional key prefix. * Use this instead of `Parameters>[0]` for a stable, readable type. * * @example * ```ts * import type { SelectorParam } from 'i18next'; * * interface CmpProps { * i18nKey: SelectorParam<'myNamespace'>; * } * ``` */ export type SelectorParam = ( src: Select, undefined>, ) => string; /// ////////////// /// /// ↆ selector ↆ /// /// ////////////// /// declare const $PluralBrand: unique symbol; /** Marks a value as coming from a plural-form key, requiring `count` in the selector options. */ export type PluralValue = T & { readonly [$PluralBrand]: typeof $PluralBrand }; declare const $SelectorKeyBrand: unique symbol; /** * A branded string produced by {@link keyFromSelector}. * Can be passed directly to `t()` when the selector API is enabled. */ export type SelectorKey = string & { readonly [$SelectorKeyBrand]: typeof $SelectorKeyBrand }; /** * Type-safe signature for {@link keyFromSelector}. * Constrains the selector callback against the default namespace's resources * (same source that `t()` uses for selectors without explicit `ns`). * When resources are not defined, accepts any selector. */ export type KeyFromSelectorFn = < Ns extends Namespace = DefaultNamespace, KPrefix extends KeyPrefix = undefined, >( selector: (src: Select, undefined>) => any, opts?: { ns?: Ns; keyPrefix?: KPrefix }, ) => SelectorKey; /** Recursively strips the {@link PluralValue} brand from a type (handles nested objects for `returnObjects`). */ export type DeepUnwrapPlural = T extends PluralValue ? U : T extends readonly any[] ? { [I in keyof T]: DeepUnwrapPlural } : T extends object ? { [K in keyof T]: DeepUnwrapPlural } : T; export type NsArg = Ns[number] | readonly Ns[number][]; export interface TFunctionSelector extends Branded { // ── Pre-computed key(s) from keyFromSelector ──────────────────────────────── // Accepts a branded `SelectorKey` (or array of them) produced by `keyFromSelector`. // Return-type precision is traded for the flexibility of decoupled key creation. // Placed first so that the more general selector overloads (below) are last — // TypeScript's `Parameters<>` utility resolves against the last call signature. = SelectorOptions>( key: SelectorKey | SelectorKey[], ...args: [options?: Opts & $Dictionary] ): DefaultTReturn; // ── Array of selectors with explicit `ns` ─────────────────────────────────── < Target extends ConstrainTarget, const NewNs extends NsArg & Namespace, const Opts extends SelectorOptions, NewSrc extends GetSource, >( selectors: readonly SelectorFn, Opts>[], options: Opts & InterpolationMap & { ns: NewNs } & _CountIfPlural, ): SelectorReturn; // ── Single selector with explicit `ns` ────────────────────────────────────── < Target extends ConstrainTarget, const NewNs extends NsArg & Namespace, const Opts extends SelectorOptions, NewSrc extends GetSource, >( selector: SelectorFn, Opts>, options: Opts & InterpolationMap> & { ns: NewNs; } & (Target extends PluralValue ? { count: number } : {}), ): SelectorReturn; // ── Array of selectors with defaultValue — preserves literal type of DV ───── // Same TypeScript limitation as the single-selector defaultValue overload below: // `const Opts` loses the `defaultValue` literal when inferred through the // conditional rest tuple of the general array overload. A plural member // requires `count`, as in the single-selector overload. < const Fns extends readonly ((src: Select) => string | object)[], const DV extends string, const Opts extends SelectorOptions = SelectorOptions, >( selectors: Fns, options: Opts & { defaultValue: DV } & _CountIfPlural<_SelectorsReturn> & InterpolationMap>>, ): SelectorReturn<_SelectorsReturn, Opts, DV>; // ── Array of selectors with default `ns` ───────────────────────────────────── // Captures the selector tuple as `const Fns` so TypeScript preserves each // element's exact return type. The union of return types is then extracted // via a distributive `infer`, which correctly handles mixed PluralValue and // plain-string callbacks that would otherwise cause TypeScript to "lock in" the // type from the first element. < const Fns extends readonly ((src: Select) => string | object)[], const Opts extends SelectorOptions = SelectorOptions, >( selectors: Fns, ...args: _SelectorArrayOptionsArg<_SelectorsReturn, Opts> ): SelectorReturn<_SelectorsReturn, Opts>; // ── Single selector with context + returnObjects ──────────────────────────── // More specific than the general context overload below. Captures `Context` as // a const generic and uses `const Fn` + `ReturnType` so FilterKeys sees the // concrete context and the callback's object/array shape is preserved (#2398). // Without this, `ConstrainTarget` / `ApplyTarget` collapse to `unknown` when // `returnObjects: true`. < const Context extends string, const Fn extends (src: Select) => any, const Opts extends SelectorOptions & { context: Context; returnObjects: true; } = SelectorOptions & { context: Context; returnObjects: true }, >( selector: Fn, options: Opts & InterpolationMap>>, ): SelectorReturn, Opts>; // ── Single selector with context — bypasses count enforcement ──────────────── // When `context` is present in options, `Target` is derived from the // context-filtered source (third mapped type of FilterKeys), which does NOT // apply the PluralValue brand. A separate overload avoids the circular // inference that would otherwise occur when `Opts['context']` sits inside the // conditional rest tuple of the overload below. < Target extends ConstrainTarget, const NewNs extends NsArg = Ns[number], const Opts extends SelectorOptions & { context: string } = SelectorOptions & { context: string; }, >( selector: SelectorFn, Opts>, options: Opts & InterpolationMap, ): SelectorReturn; // ── Single selector with defaultValue — preserves literal type of DV ──────── // `const Opts` loses literal precision for `defaultValue` when inferred // through a conditional rest tuple (TypeScript limitation). This dedicated // overload captures `DV` from a regular (non-conditional) parameter position, // preserving its literal type. Count enforcement for plural keys is achieved // via a conditional intersection on the options parameter. < const Fn extends (src: Select) => ConstrainTarget, const DV extends string, const Opts extends SelectorOptions = SelectorOptions, >( selector: Fn, options: Opts & { defaultValue: DV } & (ReturnType extends PluralValue ? { count: number } : {}) & InterpolationMap>>, ): SelectorReturn, Opts, DV>; // ── Single selector without context — enforces count for plural keys ────────── // Uses `const Fn` to capture the selector's exact return type independently of // `Opts`, breaking the circular dependency between `Target` inference and the // conditional rest tuple. `ReturnType` drives both the plural check and // the return type; `Opts` is inferred later from the resolved rest args. < const Fn extends (src: Select) => ConstrainTarget, const Opts extends SelectorOptions = SelectorOptions, >( selector: Fn, ...args: ReturnType extends PluralValue ? [options: Opts & { count: number } & InterpolationMap>>] : _SelectorOptionsArg, Opts & InterpolationMap>> ): SelectorReturn, Opts>; } export interface SelectorOptions extends Omit, $Dictionary { ns?: Ns; } export type SelectorReturn< Target, Opts extends { defaultValue?: unknown; returnObjects?: boolean }, DV = Opts['defaultValue'], > = $IsResourcesDefined extends true ? TFunctionReturnOptionalDetails, DV>, Opts> : DefaultTReturn; /** Public for react-i18next's `Trans` types (since v26.7.0). */ export interface SelectorFn> { (translations: Select): Target; } export type ApplyKeyPrefix< T extends [any], KPrefix, > = KPrefix extends `${infer Head}${_KeyPrefixSeparator}${infer Tail}` ? ApplyKeyPrefix<[T[0][Head]], Tail> : T[0][KPrefix & string]; /** Public for react-i18next's `Trans` types (since v26.7.0). */ export type ApplyTarget< Target, Opts extends { returnObjects?: unknown }, > = Opts['returnObjects'] extends true ? unknown : Target; /** Public for react-i18next's `Trans` types (since v26.7.0). */ export type ConstrainTarget> = _ReturnObjects extends true ? unknown : Opts['returnObjects'] extends true ? unknown : $IsResourcesDefined extends false ? unknown : string; export type ProcessReturnValue = $Turtles extends Target ? string : [DefaultValue] extends [never] ? Target : unknown extends DefaultValue ? Target : Target | DefaultValue; export type PickNamespaces = { [P in K as P extends keyof T ? P : never]: T[P & keyof T]; }; /** Extracts the sub-tree returned by a selector function used as keyPrefix. */ export type SelectorReturnSource = KPrefix extends (...args: any[]) => infer R ? R extends object ? R : Fallback : Fallback; /** Public for react-i18next's `Trans` types (since v26.7.0). */ export type GetSource> = KPrefix extends ( ...args: any[] ) => any ? SelectorReturnSource : KPrefix extends keyof Res ? Res[KPrefix] : undefined extends KPrefix ? Res : ApplyKeyPrefix<[Res], KPrefix>; export type Select = $IsResourcesDefined extends false ? $Turtles : [_EnableSelector] extends ['optimize'] ? T : FilterKeys; /** * Context-variant keys that are actually present (not JSON-union phantoms typed * as optional `undefined`, e.g. `transKey1_withContext?: undefined`). */ type _DefinedContextKeys = { [P in keyof T as P extends Pattern ? ([T[P]] extends [undefined] ? never : P) : never]: true; }; /** * Keys of T whose value is not `undefined` (JSON-union phantoms are typed as * optional `undefined`), built once per object. */ type _DefinedKeys = [T] extends [unknown] ? keyof { [P in keyof T as [T[P]] extends [undefined] ? never : P]: true } : never; /** * For every defined key, the prefixes K before each context separator, as * `[all, bases]`: `all` has every K with a defined key `${K}${_ContextSeparator}...`, * `bases` only those where the rest is not just a plural suffix. Jumps from one * separator occurrence to the next (so the recursion depth is the number of * separators, not the key length, which can be a whole sentence) and resumes one * character after the match, so overlapping occurrences (`a___b` with `__`) count. */ type _ContextPrefixesOf< P, Head extends string = '', All = never, Bases = never, > = P extends `${infer B}${_ContextSeparator}${string}` ? P extends `${B}${infer FromSep}` ? FromSep extends `${infer C}${infer Rest}` ? _ContextPrefixesOf< Rest, `${Head}${B}${C}`, All | `${Head}${B}`, FromSep extends | `${_PluralSeparator}${PluralSuffix}` | `${_PluralSeparator}ordinal${_PluralSeparator}${PluralSuffix}` ? Bases : Bases | `${Head}${B}` > : [All, Bases] : [All, Bases] : [All, Bases]; /** * The context prefixes of an object, built once per object (conditional type * instantiations are cached): scanning all keys for every key was quadratic * in the object size, TS2589 at about 1,000 keys with context variants. */ type _ContextPrefixes = [T] extends [unknown] ? _ContextPrefixesOf<_DefinedKeys & string> : never; type _AllContextPrefixes = [T] extends [unknown] ? _ContextPrefixes[0] : never; type _ContextBases = [T] extends [unknown] ? _ContextPrefixes[1] : never; /** Whether a string type is a single literal (not `string` or a `${string}` pattern). */ type _IsLiteral = {} extends Record ? false : true; /** * Whether T has a defined key matching Pattern: literal keys are looked up, a * pattern with a wide member scans the keys. */ type _HasDefinedKey = [ false extends (Pattern extends unknown ? _IsLiteral : never) ? keyof _DefinedContextKeys : Extract>, ] extends [never] ? false : true; type _HasContextVariant = string extends Context ? _IsLiteral extends true ? K extends _AllContextPrefixes ? true : false : _HasDefinedKey : _HasDefinedKey< T, | `${K}${_ContextSeparator}${Context & string}` | `${K}${_ContextSeparator}${Context & string}${_PluralSeparator}${PluralSuffix}` >; /** Checks whether key K has **any** context variant in T (excluding pure plural suffixes). */ type _IsContextualKey = _IsLiteral extends true ? K extends _ContextBases ? true : false : [ Exclude< keyof _DefinedContextKeys, | `${K}${_PluralSeparator}${PluralSuffix}` | `${K}${_PluralSeparator}ordinal${_PluralSeparator}${PluralSuffix}` >, ] extends [never] ? false : true; /** * Distributes {@link 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 for `returnObjects` + `context` (#2398). */ export type FilterKeys = [T] extends [readonly any[]] ? { [I in keyof T]: FilterKeys } : T extends any ? FilterKeysObject : never; export type FilterKeysObject = { // 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 extends true ? never // context variant exists, drop base key (type 3 handles it) : _IsContextualKey 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]; } & { // 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 : PluralValue; } & { // 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]; };