Created
October 7, 2023 07:52
-
-
Save cassus/cb28122d20f61d3be9c7e09d23033be9 to your computer and use it in GitHub Desktop.
i18n-ts-with-namespaces.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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