UNPKG

18.4 kBTypeScriptView Raw
1import type { $MergeBy, $PreservedValue, $Dictionary } from './helpers.js';
2
3/**
4 * This interface can be augmented by users to add types to `i18next` default TypeOptions.
5 *
6 * Usage:
7 * ```ts
8 * // i18next.d.ts
9 * import 'i18next';
10 * declare module 'i18next' {
11 * interface CustomTypeOptions {
12 * defaultNS: 'custom';
13 * returnNull: false;
14 * returnObjects: false;
15 * nsSeparator: ':';
16 * keySeparator: '.';
17 * compatibilityJSON: 'v4';
18 * allowObjectInHTMLChildren: false;
19 * resources: {
20 * custom: {
21 * foo: 'foo';
22 * };
23 * };
24 * }
25 * }
26 * ```
27 */
28export interface CustomTypeOptions {}
29
30/**
31 * This interface can be augmented by users to add types to `i18next` default PluginOptions.
32 */
33export interface CustomPluginOptions {}
34
35export type TypeOptions = $MergeBy<
36 {
37 /** @see {InitOptions.returnNull} */
38 returnNull: false;
39
40 /** @see {InitOptions.returnEmptyString} */
41 returnEmptyString: true;
42
43 /** @see {InitOptions.returnObjects} */
44 returnObjects: false;
45
46 /** @see {InitOptions.keySeparator} */
47 keySeparator: '.';
48
49 /** @see {InitOptions.nsSeparator} */
50 nsSeparator: ':';
51
52 /** @see {InitOptions.pluralSeparator} */
53 pluralSeparator: '_';
54
55 /** @see {InitOptions.contextSeparator} */
56 contextSeparator: '_';
57
58 /** @see {InitOptions.defaultNS} */
59 defaultNS: 'translation';
60
61 /** @see {InitOptions.fallbackNS} */
62 fallbackNS: false;
63
64 /** @see {InitOptions.compatibilityJSON} */
65 compatibilityJSON: 'v4';
66
67 /** @see {InitOptions.resources} */
68 resources: object;
69
70 /**
71 * Flag that allows HTML elements to receive objects. This is only useful for React applications
72 * where you pass objects to HTML elements so they can be replaced to their respective interpolation
73 * values (mostly with Trans component)
74 */
75 allowObjectInHTMLChildren: false;
76
77 /**
78 * Flag that enables strict key checking even if a `defaultValue` has been provided.
79 * This ensures all calls of `t` function don't accidentally use implicitly missing keys.
80 */
81 strictKeyChecks: false;
82
83 /**
84 * Prefix for interpolation
85 */
86 interpolationPrefix: '{{';
87
88 /**
89 * Suffix for interpolation
90 */
91 interpolationSuffix: '}}';
92
93 /** @see {InterpolationOptions.unescapePrefix} */
94 unescapePrefix: '-';
95
96 /** @see {InterpolationOptions.unescapeSuffix} */
97 unescapeSuffix: '';
98 },
99 CustomTypeOptions
100>;
101
102export type PluginOptions<T> = $MergeBy<
103 {
104 /**
105 * Options for language detection - check documentation of plugin
106 * @default undefined
107 */
108 detection?: object;
109
110 /**
111 * Options for backend - check documentation of plugin
112 * @default undefined
113 */
114 backend?: T;
115
116 /**
117 * Options for cache layer - check documentation of plugin
118 * @default undefined
119 */
120 cache?: object;
121
122 /**
123 * Options for i18n message format - check documentation of plugin
124 * @default undefined
125 */
126 i18nFormat?: object;
127 },
128 CustomPluginOptions
129>;
130
131export type FormatFunction = (
132 value: any,
133 format?: string,
134 lng?: string,
135 options?: InterpolationOptions & $Dictionary<any>,
136) => string;
137
138export interface InterpolationOptions {
139 /**
140 * Format function see formatting for details
141 * @default noop
142 */
143 format?: FormatFunction;
144 /**
145 * Used to separate format from interpolation value
146 * @default ','
147 */
148 formatSeparator?: string;
149 /**
150 * Escape function
151 * @default str => str
152 */
153 escape?(str: string): string;
154
155 /**
156 * Always format interpolated values.
157 * @default false
158 */
159 alwaysFormat?: boolean;
160 /**
161 * Escape passed in values to avoid xss injection
162 * @default true
163 */
164 escapeValue?: boolean;
165 /**
166 * If true, then value passed into escape function is not casted to string, use with custom escape function that does its own type check
167 * @default false
168 */
169 useRawValueToEscape?: boolean;
170 /**
171 * Prefix for interpolation
172 * @default '{{'
173 */
174 prefix?: string;
175 /**
176 * Suffix for interpolation
177 * @default '}}'
178 */
179 suffix?: string;
180 /**
181 * Escaped prefix for interpolation (regexSafe)
182 * @default undefined
183 */
184 prefixEscaped?: string;
185 /**
186 * Escaped suffix for interpolation (regexSafe)
187 * @default undefined
188 */
189 suffixEscaped?: string;
190 /**
191 * Suffix to unescaped mode
192 * @default undefined
193 */
194 unescapeSuffix?: string;
195 /**
196 * Prefix to unescaped mode
197 * @default '-'
198 */
199 unescapePrefix?: string;
200 /**
201 * Prefix for nesting
202 * @default '$t('
203 */
204 nestingPrefix?: string;
205 /**
206 * Suffix for nesting
207 * @default ')'
208 */
209 nestingSuffix?: string;
210 /**
211 * Escaped prefix for nesting (regexSafe)
212 * @default undefined
213 */
214 nestingPrefixEscaped?: string;
215 /**
216 * Escaped suffix for nesting (regexSafe)
217 * @default undefined
218 */
219 nestingSuffixEscaped?: string;
220 /**
221 * Separates options from key
222 * @default ','
223 */
224 nestingOptionsSeparator?: string;
225 /**
226 * Global variables to use in interpolation replacements
227 * @default undefined
228 */
229
230 defaultVariables?: { [index: string]: any };
231 /**
232 * After how many interpolation runs to break out before throwing a stack overflow
233 * @default 1000
234 */
235 maxReplaces?: number;
236
237 /**
238 * If true, it will skip to interpolate the variables
239 * @default true
240 */
241 skipOnVariables?: boolean;
242}
243
244export interface FallbackLngObjList {
245 [language: string]: readonly string[];
246}
247
248export type FallbackLng =
249 | string
250 | readonly string[]
251 | FallbackLngObjList
252 | ((code: string) => string | readonly string[] | FallbackLngObjList);
253
254export interface ReactOptions {
255 /**
256 * Set it to fallback to let passed namespaces to translated hoc act as fallbacks
257 * @default 'default'
258 */
259 nsMode?: 'default' | 'fallback';
260 /**
261 * Set it to the default parent element created by the Trans component.
262 * @default 'div'
263 */
264 defaultTransParent?: string;
265 /**
266 * Set which events trigger a re-render, can be set to false or string of events
267 * @default 'languageChanged'
268 */
269 bindI18n?: string | false;
270 /**
271 * Set which events on store trigger a re-render, can be set to false or string of events
272 * @default ''
273 */
274 bindI18nStore?: string | false;
275 /**
276 * Set fallback value for Trans components without children
277 * @default undefined
278 */
279 transEmptyNodeValue?: string;
280 /**
281 * Set it to false if you do not want to use Suspense
282 * @default true
283 */
284 useSuspense?: boolean;
285 /**
286 * Function to generate an i18nKey from the defaultValue (or Trans children)
287 * when no key is provided.
288 * By default, the defaultValue (Trans text) itself is used as the key.
289 * If you want to require keys for all translations, supply a function
290 * that always throws an error.
291 * @default undefined
292 */
293 hashTransKey?(defaultValue: TOptionsBase['defaultValue']): TOptionsBase['defaultValue'];
294 /**
295 * Convert eg. <br/> found in translations to a react component of type br
296 * @default true
297 */
298 transSupportBasicHtmlNodes?: boolean;
299 /**
300 * Which nodes not to convert in defaultValue generation in the Trans component.
301 * @default ['br', 'strong', 'i', 'p']
302 */
303 transKeepBasicHtmlNodesFor?: readonly string[];
304 /**
305 * Wrap text nodes in a user-specified element.
306 * @default ''
307 */
308 transWrapTextNodes?: string;
309 /**
310 * Optional keyPrefix that will be automatically applied to returned t function in useTranslation for example.
311 * @default undefined
312 */
313 keyPrefix?: string;
314 /**
315 * Unescape function
316 * by default it unescapes some basic html entities
317 */
318 unescape?(str: string): string;
319}
320
321export type ResourceKey =
322 | string
323 | {
324 [key: string]: any;
325 };
326
327export interface ResourceLanguage {
328 [namespace: string]: ResourceKey;
329}
330
331export interface Resource {
332 [language: string]: ResourceLanguage;
333}
334
335export interface InitOptions<T = object> extends PluginOptions<T> {
336 /**
337 * Logs info level to console output. Helps finding issues with loading not working.
338 * @default false
339 */
340 debug?: boolean;
341
342 /**
343 * Resources to initialize with (if not using loading or not appending using addResourceBundle)
344 * @default undefined
345 */
346 resources?: Resource;
347
348 /**
349 * Allow initializing with bundled resources while using a backend to load non bundled ones.
350 * @default false
351 */
352 partialBundledLanguages?: boolean;
353
354 /**
355 * Language to use (overrides language detection)
356 * @default undefined
357 */
358 lng?: string;
359
360 /**
361 * Language to use if translations in user language are not available.
362 * @default 'dev'
363 */
364 fallbackLng?: false | FallbackLng;
365
366 /**
367 * Array of allowed languages
368 * @default false
369 */
370 supportedLngs?: false | readonly string[];
371
372 /**
373 * If true will pass eg. en-US if finding en in supportedLngs
374 * @default false
375 */
376 nonExplicitSupportedLngs?: boolean;
377
378 /**
379 * Language codes to lookup, given set language is
380 * 'en-US': 'all' --> ['en-US', 'en', 'dev'],
381 * 'currentOnly' --> 'en-US',
382 * 'languageOnly' --> 'en'
383 * @default 'all'
384 */
385 load?: 'all' | 'currentOnly' | 'languageOnly';
386
387 /**
388 * Array of languages to preload. Important on server-side to assert translations are loaded before rendering views.
389 * @default false
390 */
391 preload?: false | readonly string[];
392
393 /**
394 * Language will be lowercased eg. en-US --> en-us
395 * @default false
396 */
397 lowerCaseLng?: boolean;
398
399 /**
400 * Language will be lowercased EN --> en while leaving full locales like en-US
401 * @default false
402 */
403 cleanCode?: boolean;
404
405 /**
406 * String or array of namespaces to load
407 * @default 'translation'
408 */
409 ns?: string | readonly string[];
410
411 /**
412 * Default namespace used if not passed to translation function
413 * @default 'translation'
414 */
415 defaultNS?: string | false | readonly string[];
416
417 /**
418 * String or array of namespaces to lookup key if not found in given namespace.
419 * @default false
420 */
421 fallbackNS?: false | string | readonly string[];
422
423 /**
424 * Calls save missing key function on backend if key not found.
425 * @default false
426 */
427 saveMissing?: boolean;
428
429 /**
430 * Calls save missing key function on backend if key not found also for plural forms.
431 * @default false
432 */
433 saveMissingPlurals?: boolean;
434
435 /**
436 * Experimental: enable to update default values using the saveMissing
437 * (Works only if defaultValue different from translated value.
438 * Only useful on initial development or when keeping code as source of truth not changing values outside of code.
439 * Only supported if backend supports it already)
440 * @default false
441 */
442 updateMissing?: boolean;
443
444 /**
445 * @default 'fallback'
446 */
447 saveMissingTo?: 'current' | 'all' | 'fallback';
448
449 /**
450 * Used to not fallback to the key as default value, when using saveMissing functionality.
451 * i.e. when using with i18next-http-backend this will result in having a key with an empty string value.
452 * @default false
453 */
454 missingKeyNoValueFallbackToKey?: boolean;
455
456 /**
457 * Used for custom missing key handling (needs saveMissing set to true!)
458 * @default false
459 */
460 missingKeyHandler?:
461 | false
462 | ((
463 lngs: readonly string[],
464 ns: string,
465 key: string,
466 fallbackValue: string,
467 updateMissing: boolean,
468 options: any,
469 ) => void);
470
471 /**
472 * Receives a key that was not found in `t()` and returns a value, that will be returned by `t()`
473 * @default noop
474 */
475 parseMissingKeyHandler?(key: string, defaultValue?: string): any;
476
477 /**
478 * Appends namespace to missing key
479 * @default false
480 */
481 appendNamespaceToMissingKey?: boolean;
482
483 /**
484 * Gets called in case a interpolation value is undefined. This method will not be called if the value is empty string or null
485 * @default noop
486 */
487 missingInterpolationHandler?: (text: string, value: any, options: InitOptions) => any;
488
489 /**
490 * Will use 'plural' as suffix for languages only having 1 plural form, setting it to false will suffix all with numbers
491 * @default true
492 */
493 simplifyPluralSuffix?: boolean;
494
495 /**
496 * String or array of postProcessors to apply per default
497 * @default false
498 */
499 postProcess?: false | string | readonly string[];
500
501 /**
502 * passthrough the resolved object including 'usedNS', 'usedLang' etc into options object of postprocessors as 'i18nResolved' property
503 * @default false
504 */
505 postProcessPassResolved?: boolean;
506
507 /**
508 * Allows null values as valid translation
509 * @default false
510 */
511 returnNull?: boolean;
512
513 /**
514 * Allows empty string as valid translation
515 * @default true
516 */
517 returnEmptyString?: boolean;
518
519 /**
520 * Allows objects as valid translation result
521 * @default false
522 */
523 returnObjects?: boolean;
524
525 /**
526 * Returns an object that includes information about the used language, namespace, key and value
527 * @default false
528 */
529 returnDetails?: boolean;
530
531 /**
532 * Gets called if object was passed in as key but returnObjects was set to false
533 * @default noop
534 */
535 returnedObjectHandler?(key: string, value: string, options: any): void;
536
537 /**
538 * Char, eg. '\n' that arrays will be joined by
539 * @default false
540 */
541 joinArrays?: false | string;
542
543 /**
544 * Sets defaultValue
545 * @default args => ({ defaultValue: args[1] })
546 */
547 overloadTranslationOptionHandler?(args: string[]): TOptions;
548
549 /**
550 * @see https://www.i18next.com/translation-function/interpolation
551 */
552 interpolation?: InterpolationOptions;
553
554 /**
555 * Options for react - check documentation of plugin
556 * @default undefined
557 */
558 react?: ReactOptions;
559
560 /**
561 * Triggers resource loading in init function inside a setTimeout (default async behaviour).
562 * Set it to false if your backend loads resources sync - that way calling i18next.t after
563 * init is possible without relaying on the init callback.
564 * @default true
565 */
566 initAsync?: boolean;
567
568 /**
569 * @deprecated Use initAsync instead.
570 */
571 initImmediate?: boolean;
572
573 /**
574 * Char to separate keys
575 * @default '.'
576 */
577 keySeparator?: false | string;
578
579 /**
580 * Char to split namespace from key
581 * @default ':'
582 */
583 nsSeparator?: false | string;
584
585 /**
586 * Char to split plural from key
587 * @default '_'
588 */
589 pluralSeparator?: string;
590
591 /**
592 * Char to split context from key
593 * @default '_'
594 */
595 contextSeparator?: string;
596
597 /**
598 * Prefixes the namespace to the returned key when using `cimode`
599 * @default false
600 */
601 appendNamespaceToCIMode?: boolean;
602
603 /**
604 * Compatibility JSON version
605 * @warning only `v4` is available and supported by typescript
606 * @default 'v4'
607 */
608 compatibilityJSON?: 'v4';
609
610 /**
611 * Options for https://github.com/locize/locize-lastused
612 * @default undefined
613 */
614 locizeLastUsed?: {
615 /**
616 * The id of your locize project
617 */
618 projectId: string;
619
620 /**
621 * An api key if you want to send missing keys
622 */
623 apiKey?: string;
624
625 /**
626 * The reference language of your project
627 * @default 'en'
628 */
629 referenceLng?: string;
630
631 /**
632 * Version
633 * @default 'latest'
634 */
635 version?: string;
636
637 /**
638 * Debounce interval to send data in milliseconds
639 * @default 90000
640 */
641 debounceSubmit?: number;
642
643 /**
644 * Hostnames that are allowed to send last used data.
645 * Please keep those to your local system, staging, test servers (not production)
646 * @default ['localhost']
647 */
648 allowedHosts?: readonly string[];
649 };
650
651 /**
652 * Automatically lookup for a flat key if a nested key is not found an vice-versa
653 * @default true
654 */
655 ignoreJSONStructure?: boolean;
656
657 /**
658 * Limit parallelism of calls to backend
659 * This is needed to prevent trying to open thousands of
660 * sockets or file descriptors, which can cause failures
661 * and actually make the entire process take longer.
662 * @default 10
663 */
664 maxParallelReads?: number;
665
666 /**
667 * The maximum number of retries to perform.
668 * Note that retries are only performed when a request has no response
669 * and throws an error.
670 * The default value is used if value is set below 0.
671 * @default 5
672 */
673 maxRetries?: number;
674
675 /**
676 * Set how long to wait, in milliseconds, between retries of failed requests.
677 * This number is compounded by a factor of 2 for subsequent retry.
678 * The default value is used if value is set below 1ms.
679 * @default 350
680 */
681 retryTimeout?: number;
682}
683
684export interface TOptionsBase {
685 /**
686 * Default value to return if a translation was not found
687 */
688 defaultValue?: unknown;
689 /**
690 * Count value used for plurals
691 */
692 count?: number;
693 /**
694 * Ordinal flag for ordinal plurals
695 */
696 ordinal?: boolean;
697 /**
698 * Used for contexts (eg. male\female)
699 */
700 context?: unknown;
701 /**
702 * Object with vars for interpolation - or put them directly in options
703 */
704 replace?: any;
705 /**
706 * Override language to use
707 */
708 lng?: string;
709 /**
710 * Override languages to use
711 */
712 lngs?: readonly string[];
713 /**
714 * Override language to lookup key if not found see fallbacks for details
715 */
716 fallbackLng?: FallbackLng;
717 /**
718 * Override namespaces (string or array)
719 */
720 ns?: Namespace;
721 /**
722 * Override char to separate keys
723 */
724 keySeparator?: false | string;
725 /**
726 * Override char to split namespace from key
727 */
728 nsSeparator?: false | string;
729 /**
730 * Accessing an object not a translation string (can be set globally too)
731 */
732 returnObjects?: boolean;
733 /**
734 * Returns an object that includes information about the used language, namespace, key and value
735 */
736 returnDetails?: boolean;
737 /**
738 * Char, eg. '\n' that arrays will be joined by (can be set globally too)
739 */
740 joinArrays?: string;
741 /**
742 * String or array of postProcessors to apply see interval plurals as a sample
743 */
744 postProcess?: string | readonly string[];
745 /**
746 * Override interpolation options
747 */
748 interpolation?: InterpolationOptions;
749}
750
751export type TOptions<TInterpolationMap extends object = $Dictionary> = TOptionsBase &
752 TInterpolationMap;
753
754export type FlatNamespace = $PreservedValue<keyof TypeOptions['resources'], string>;
755export type Namespace<T = FlatNamespace> = T | readonly T[];
756export type DefaultNamespace = TypeOptions['defaultNS'];