From 921368feadfd7ececeebb8aa13876e60a1da7439 Mon Sep 17 00:00:00 2001 From: Aral Roca Gomez Date: Mon, 17 Jul 2023 20:12:21 +0200 Subject: [PATCH] docs: enable type-safety consuming translations (#1109) --- docs/type-safety.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 docs/type-safety.md diff --git a/docs/type-safety.md b/docs/type-safety.md new file mode 100644 index 00000000..6d5bdccf --- /dev/null +++ b/docs/type-safety.md @@ -0,0 +1,39 @@ +# Type safety consuming translations + +To enable type safety consuming translations, you have to add this to the `next-translate.d.ts` file specifying the name and location of the namespaces: + +```ts +import type { Paths, I18n, Translate } from 'next-translate' + +export interface TranslationsKeys { + // Example with "common" and "home" namespaces in "en" (the default language): + common: Paths + home: Paths + // Specify here all the namespaces you have... +} + +export interface TypeSafeTranslate + extends Omit { + t: { + ( + key: TranslationsKeys[Namespace], + ...rest: Tail> + ): string + (template: TemplateStringsArray): string + } +} + +declare module 'next-translate/useTranslation' { + export default function useTranslation< + Namespace extends keyof TranslationsKeys + >(namespace: Namespace): TypeSafeTranslate +} +``` + +Then type safety should work: + +Screenshot 2023-07-17 at 19 17 13 + +Screenshot 2023-07-17 at 19 22 00 + +Reference: https://github.com/aralroca/next-translate/pull/1108