UNPKG

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