-
for translating the error messages in zod, i wanted to pass the t function to a generator function zod. the idea works as intended on both dev and build mode. now i want to see if i can add typescript support. any idea how i can achieve this?
|
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 6 replies
-
is this even an accepted pattern? |
Beta Was this translation helpful? Give feedback.
-
would love to see an answer as well |
Beta Was this translation helpful? Give feedback.
-
You can use this as the function type import type { NestedKeyOf } from "next-intl";
type TranslateFn = (path: NextedKeyOf<IntlMessages>): string; And make sure you have this somewhere in a type Messages = typeof import("./../translations/en.json");
declare interface IntlMessages extends Messages {} Or replace The tradeoff of this type is that you can't pass some of the path to use translation hook: const t = useTranslation("namespace");
// it has to be
const t = useTranslation(); Another way I use with zod, is making the message is the key const schema = z.object({
password: z.string({ required_error: "errors.password-required" }).min(8, "errors.password-length");
})
// And, when rendering the error message I do:
<P>{error.message.startsWith("errors.") ? t(error.message) : error.message}</p>
// You can also prefix the localized messages with a fake prefix and remove it later
const schema = z.object({
password: z.string({ required_error: "intl:login.password-required" }).min(8, "intl:login.password-length");
})
<P>{error.message.startsWith("intl:") ? t(error.message.replace("int:", "")) : error.message}</p>
// To get type completion for error messages, you can do:
```ts
// fake function
const t: TranslateFn = (key) => key;
const schema = z.object({
password: z.string({ required_error: t("errors.password-required") }).min(8, t("errors.password-length"));
}) |
Beta Was this translation helpful? Give feedback.
-
This is not the « recommended pattern », but in my humble opinion it does exactly what we want and I love using it : import type { useTranslations } from "next-intl";
import type { getTranslations } from "next-intl/server";
export type TFn =
| ReturnType<typeof useTranslations<never>>
| Awaited<ReturnType<typeof getTranslations<never>>>;
const yourCustomCode = (t: TFn) => {
// Your code
} Is the simplest way to export it. Recommended way is here #1134 but I don't like it much |
Beta Was this translation helpful? Give feedback.
This is not the « recommended pattern », but in my humble opinion it does exactly what we want and I love using it :
Is the simplest way to export it.
Recommended way is here #1134 but I don't like it much