diff --git a/docs/type-safety.md b/docs/type-safety.md index ea9daf0..43532dd 100644 --- a/docs/type-safety.md +++ b/docs/type-safety.md @@ -14,22 +14,32 @@ export interface TranslationsKeys { // Specify here all the namespaces you have... } -export interface TypeSafeTranslate +type TranslationNamespace = keyof TranslationsKeys; + +export interface TranslateFunction { + ( + key: TranslationsKeys[Namespace], + ...rest: Tail> + ): string + (template: TemplateStringsArray): string +}; + +export interface TypeSafeTranslate extends Omit { - t: { - ( - key: TranslationsKeys[Namespace], - ...rest: Tail> - ): string - (template: TemplateStringsArray): string - } + t: TranslateFunction } declare module 'next-translate/useTranslation' { export default function useTranslation< - Namespace extends keyof TranslationsKeys + Namespace extends TranslationNamespace >(namespace: Namespace): TypeSafeTranslate } + +declare module 'next-translate/getT' { + export default function getT< + Namespace extends TranslationNamespace + >(locale?: string, namespace: Namespace): Promise> +} ``` Then type safety should work: @@ -38,4 +48,4 @@ Then type safety should work: Screenshot 2023-07-17 at 19 22 00 -Reference: https://github.com/aralroca/next-translate/pull/1108 +Reference: diff --git a/examples/with-app-directory/next-translate.d.ts b/examples/with-app-directory/next-translate.d.ts index ea3fac6..ed1185a 100644 --- a/examples/with-app-directory/next-translate.d.ts +++ b/examples/with-app-directory/next-translate.d.ts @@ -1,23 +1,37 @@ import type { Paths, I18n, Translate } from 'next-translate' +type Tail = T extends [unknown, ...infer Rest] ? Rest : never; + 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 +type TranslationNamespace = keyof TranslationsKeys; + +export interface TranslateFunction { + ( + key: TranslationsKeys[Namespace], + ...rest: Tail> + ): string + (template: TemplateStringsArray): string +}; + +export interface TypeSafeTranslate extends Omit { - t: { - ( - key: TranslationsKeys[Namespace], - ...rest: Tail> - ): string - (template: TemplateStringsArray): string - } + t: TranslateFunction } declare module 'next-translate/useTranslation' { export default function useTranslation< - Namespace extends keyof TranslationsKeys + Namespace extends TranslationNamespace >(namespace: Namespace): TypeSafeTranslate } + +declare module 'next-translate/getT' { + export default function getT< + Namespace extends TranslationNamespace + >(locale?: string, namespace: Namespace): Promise> +}