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

Make getFixedT type-safe #1860

Merged
merged 1 commit into from Oct 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 14 additions & 6 deletions index.d.ts
Expand Up @@ -824,7 +824,7 @@ type TypeOptionsFallback<TranslationValue, Option, MatchingValue> = Option exten
/**
* Checks if user has enabled `returnEmptyString` and `returnNull` options to retrieve correct values.
*/
interface CustomTypeParameters {
interface CustomTypeParameters {
returnNull?: boolean;
returnEmptyString?: boolean;
}
Expand Down Expand Up @@ -1184,12 +1184,20 @@ export interface i18n {
*
* Accepts optional keyPrefix that will be automatically applied to returned t function.
*/
getFixedT(
getFixedT<N extends Namespace = DefaultNamespace, TKPrefix extends KeyPrefix<N> = undefined>(
lng: string | readonly string[],
ns?: string | readonly string[],
keyPrefix?: string,
): TFunction;
getFixedT(lng: null, ns: string | readonly string[] | null, keyPrefix?: string): TFunction;
ns?: N,
keyPrefix?: TKPrefix,
): TFunction<N, TKPrefix>;
getFixedT<
N extends Namespace | null,
TKPrefix extends KeyPrefix<ActualNS>,
ActualNS extends Namespace = N extends null ? DefaultNamespace : N,
>(
lng: null,
ns: N,
keyPrefix?: TKPrefix,
): TFunction<ActualNS, TKPrefix>;

/**
* Changes the language. The callback will be called as soon translations were loaded or an error occurs while loading.
Expand Down
20 changes: 20 additions & 0 deletions test/typescript/custom-types/getFixedT.test.ts
@@ -0,0 +1,20 @@
import i18next from 'i18next';

const t1 = i18next.getFixedT(null, null, 'foo');

const t2 = i18next.getFixedT(null, 'alternate', 'foobar.deep');
t2('deeper.deeeeeper');
t2('deeper').deeeeeper;

const t3 = i18next.getFixedT('en');
t3('foo');

const t4 = i18next.getFixedT('en', 'alternate', 'foobar');
t4('barfoo');

// @ts-expect-error
const t5 = i18next.getFixedT(null, null, 'xxx');

const t6 = i18next.getFixedT(null, 'alternate', 'foobar');
// @ts-expect-error
t6('xxx');