amannn / next-intl

🌐 Internationalization (i18n) for Next.js
https://next-intl-docs.vercel.app
MIT License
2.58k stars 236 forks source link

TypeScript raises an error when using dynamic keys for translations with next-intl (example with zod) #1521

Closed jeremy-habit closed 1 week ago

jeremy-habit commented 1 week ago

Description

When using next-intl with TypeScript, dynamic keys for accessing translation messages are causing TypeScript to raise errors. This issue occurs because TypeScript expects a strict type for message keys, making it difficult to use dynamic values or variables as keys. For example, when i want to translate an error message from zod like this: t(errors?.forname?.message)

TypeScript throws an error when a dynamic key is used, as it enforces the type to match exactly one of the known keys. This makes it challenging to handle cases where the translation key is generated dynamically.

Verifications

Mandatory reproduction URL

https://github.com/amannn/next-intl-bug-repro-app-router

Reproduction description

imagine than toto is en error message from zod :

const t = useTranslations('Error'); const toto: string | undefined = 'dynamic_key_but_valid_key_string'; t(toto); // ts error here

Expected behaviour

Proposed Solutions or Workarounds

1.  Relax TypeScript validation for translation keys: Allow an option to opt out of strict typing for dynamic keys, so that TypeScript does not enforce exact match validation in such cases.
2.  Provide a function or wrapper to handle dynamic keys: Create a utility function that allows using dynamic keys while still checking against the type definition in other cases.
amannn commented 1 week ago

Yep, this is expected. If you want strict validation of keys, this is what next-intl will give you. If you want to disable type validation for certain cases, you can of course use // @ts-ignore.

Here's btw. a Zod example that doesn't have this issue: When using Zod for validation, how can I localize error messages?

jeremy-habit commented 1 week ago

Yep, this is expected. If you want strict validation of keys, this is what next-intl will give you. If you want to disable type validation for certain cases, you can of course use // @ts-ignore.

Here's btw. a Zod example that doesn't have this issue: When using Zod for validation, how can I localize error messages?

Thank you for your answer. I saw the zod example but i'm using react-hook-form with zod and next-intl, and i'm validating my form by the 'onChange' mode, and not at the submit. I don't really know how i can use server action from your example to resolve my problem in this case. Do you ? @amannn thank you

amannn commented 1 week ago

Maybe this helps: https://github.com/amannn/next-intl/discussions/437#discussioncomment-9873018