UNPKG

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