From f46311d3ee47b3d54ec46c21122fdff0ae8242c0 Mon Sep 17 00:00:00 2001 From: Pedro Durek Date: Thu, 27 Oct 2022 00:38:01 -0600 Subject: [PATCH] Make getFixedT type-safe --- index.d.ts | 20 +++++++++++++------ .../typescript/custom-types/getFixedT.test.ts | 20 +++++++++++++++++++ 2 files changed, 34 insertions(+), 6 deletions(-) create mode 100644 test/typescript/custom-types/getFixedT.test.ts diff --git a/index.d.ts b/index.d.ts index 902ad445c..447b60e66 100644 --- a/index.d.ts +++ b/index.d.ts @@ -824,7 +824,7 @@ type TypeOptionsFallback = Option exten /** * Checks if user has enabled `returnEmptyString` and `returnNull` options to retrieve correct values. */ - interface CustomTypeParameters { +interface CustomTypeParameters { returnNull?: boolean; returnEmptyString?: boolean; } @@ -1184,12 +1184,20 @@ export interface i18n { * * Accepts optional keyPrefix that will be automatically applied to returned t function. */ - getFixedT( + getFixedT = 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; + getFixedT< + N extends Namespace | null, + TKPrefix extends KeyPrefix, + ActualNS extends Namespace = N extends null ? DefaultNamespace : N, + >( + lng: null, + ns: N, + keyPrefix?: TKPrefix, + ): TFunction; /** * Changes the language. The callback will be called as soon translations were loaded or an error occurs while loading. diff --git a/test/typescript/custom-types/getFixedT.test.ts b/test/typescript/custom-types/getFixedT.test.ts new file mode 100644 index 000000000..d8c33b433 --- /dev/null +++ b/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');