react-i18next icon indicating copy to clipboard operation
react-i18next copied to clipboard

Type instantiation is excessively deep and possibly infinite.ts(2589)

Open Micro-sun opened this issue 1 year ago • 1 comments

use "react-i18next": "^11.16.3", but have an error "Type instantiation is excessively deep and possibly infinite.ts(2589)" or have one meet before?

Micro-sun avatar Jul 02 '24 03:07 Micro-sun

Update all i18next dependencies. If you still have that issue, please provide a minimal reproducible example repository.

adrai avatar Jul 02 '24 04:07 adrai

Issue

When calling const { t } = useTranslation(); in a React application using i18next, I encountered the following TypeScript error: Type instantiation is excessively deep and possibly infinite

This issue only occurred when the translation JSON file was heavily nested.

Steps to Reproduce

Create a JSON file with deeply nested translation objects (e.g., five or more levels deep).

  1. Load the file into your React application using i18next.
  2. Import and call useTranslation() in a React component.
  3. Observe that TypeScript sometimes reports the error: Type instantiation is excessively deep and possibly infinite

Suggested Solution

Flatten your nested JSON keys using dot notation. For example, convert:

{
  "page_1": {
    "title": "This is a title.",
    "description": "This is a description",
    "button": "Click me!"
  }
}

into:

{
  "page_1.title": "This is a title.",
  "page_1.description": "This is a description",
  "page_1.button": "Click me!"
}

By doing so, TypeScript can handle the translation types without exceeding recursion limits.

Additional Context

  • I wrote a custom function to perform the flattening, but there are existing packages that handle this task.
  • After flattening, my file with 517 lines (and up to five levels of nesting) worked fine with no errors.
  • The exact maximum nested size before hitting the TypeScript limit is unclear, but flattening appears to be a reliable workaround.

Environment

  • i18next version: ^15.0.2
  • React version: ^18.2.0
  • TypeScript version: 5.7.2

Possible Workarounds

  • Use an existing package to flatten your JSON files automatically.
  • Keep nesting to a minimum in your translation files.

Please let me know if there are any further details I can provide!

lucas-dtrn avatar Jan 06 '25 16:01 lucas-dtrn

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Apr 26 '25 02:04 stale[bot]

Had this issue. Turns out I had accidentally removed the exports from the end of my en-US.ts file.

zachTrio avatar May 09 '25 01:05 zachTrio