-
-
Notifications
You must be signed in to change notification settings - Fork 206
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add type safety for getT function (#1184)
* Update type-safety.md * Update next-translate.d.ts with new TranslateFunction interface * Refactor translation types in next-translate.d.ts * Refactor type safety in TranslateFunction
- Loading branch information
1 parent
c3b71ad
commit 17df895
Showing
2 changed files
with
43 additions
and
19 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,37 @@ | ||
import type { Paths, I18n, Translate } from 'next-translate' | ||
|
||
type Tail<T> = T extends [unknown, ...infer Rest] ? Rest : never; | ||
|
||
export interface TranslationsKeys { | ||
// Example with "common" and "home" namespaces in "en" (the default language): | ||
common: Paths<typeof import('./locales/en/common.json')> | ||
home: Paths<typeof import('./locales/en/home.json')> | ||
// Specify here all the namespaces you have... | ||
} | ||
|
||
export interface TypeSafeTranslate<Namespace extends keyof TranslationsKeys> | ||
type TranslationNamespace = keyof TranslationsKeys; | ||
|
||
export interface TranslateFunction<Namespace extends TranslationNamespace> { | ||
( | ||
key: TranslationsKeys[Namespace], | ||
...rest: Tail<Parameters<Translate>> | ||
): string | ||
<T extends string>(template: TemplateStringsArray): string | ||
}; | ||
|
||
export interface TypeSafeTranslate<Namespace extends TranslationNamespace> | ||
extends Omit<I18n, 't'> { | ||
t: { | ||
( | ||
key: TranslationsKeys[Namespace], | ||
...rest: Tail<Parameters<Translate>> | ||
): string | ||
<T extends string>(template: TemplateStringsArray): string | ||
} | ||
t: TranslateFunction<Namespace> | ||
} | ||
|
||
declare module 'next-translate/useTranslation' { | ||
export default function useTranslation< | ||
Namespace extends keyof TranslationsKeys | ||
Namespace extends TranslationNamespace | ||
>(namespace: Namespace): TypeSafeTranslate<Namespace> | ||
} | ||
|
||
declare module 'next-translate/getT' { | ||
export default function getT< | ||
Namespace extends TranslationNamespace | ||
>(locale?: string, namespace: Namespace): Promise<TranslateFunction<Namespace>> | ||
} |