Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add Paths type for type safety #1108

Merged
merged 2 commits into from Jul 17, 2023
Merged

feat: add Paths type for type safety #1108

merged 2 commits into from Jul 17, 2023

Conversation

aralroca
Copy link
Owner

Related with #721

After this feature (adding Paths), is possible to define next-translate.d.ts like this:

import type { Paths, I18n, Translate } from 'next-translate'

export interface TranslationsKeys {
  common: Paths<typeof import('./locales/en/common.json')>
  home: Paths<typeof import('./locales/en/home.json')>
}

export interface TypeSafeTranslate<Namespace extends keyof TranslationsKeys>
  extends Omit<I18n, 't'> {
  t: {
    (
      key: TranslationsKeys[Namespace],
      ...rest: Tail<Parameters<Translate>>
    ): string
    <T extends string>(template: TemplateStringsArray): string
  }
}

declare module 'next-translate/useTranslation' {
  export default function useTranslation<
    Namespace extends keyof TranslationsKeys
  >(namespace: Namespace): TypeSafeTranslate<Namespace>
}

Then type safety should work:

Screenshot 2023-07-17 at 19 17 13 Screenshot 2023-07-17 at 19 22 00

@aralroca aralroca merged commit f152419 into master Jul 17, 2023
6 checks passed
@aralroca aralroca deleted the add-paths-type-safety branch July 17, 2023 18:02
@itxtoledo
Copy link

Awesome!

@matthewlewandowski93
Copy link

So awesome!
Just in case anyone else runs into this, the inline imports did not work for me, but this did.

import home from "./locales/en/home.json";
import common from "./locales/en/common.json";

export interface TranslationsKeys {
  common: Paths<typeof common>;
  home: Paths<typeof home>;
}

@hichemfantar
Copy link
Contributor

@aralroca this doesn't seem to work with the getT function.

any ideas on how to get it to work?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants