Skip to content

Instantly share code, notes, and snippets.

@cassus
Created October 7, 2023 07:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cassus/cb28122d20f61d3be9c7e09d23033be9 to your computer and use it in GitHub Desktop.
Save cassus/cb28122d20f61d3be9c7e09d23033be9 to your computer and use it in GitHub Desktop.
i18n-ts-with-namespaces.ts
import type { Paths, I18n, Translate } from "next-translate"
type Tail<T> = T extends [unknown, ...infer Rest] ? Rest : never
export type TranslationsKeys = {
common: Paths<typeof import("./locales/en/common.json")>
["feat-analytics"]: Paths<typeof import("./locales/en/feat-analytics.json")>
["feat-participate"]: Paths<
typeof import("./locales/en/feat-participate.json")
>
["feat-results"]: Paths<typeof import("./locales/en/feat-results.json")>
}
type NamespacedTranslationKeys = {
[Namespace in keyof TranslationsKeys]: `${Namespace}:${TranslationsKeys[Namespace]}`
}[keyof TranslationsKeys]
export type TypeSafeTranslate<Namespace extends keyof TranslationsKeys> = {
t: {
(
key: TranslationsKeys[Namespace] | NamespacedTranslationKeys,
...rest: Tail<Parameters<Translate>>
): string
<T extends string>(template: TemplateStringsArray): string
}
} & Omit<I18n, "t">
declare module "next-translate/useTranslation" {
export default function useTranslation<
Namespace extends keyof TranslationsKeys,
>(namespace: Namespace): TypeSafeTranslate<Namespace>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment