Wire up typescript safety net around i18next

This commit is contained in:
Michael Telatynski
2023-11-17 12:26:25 +00:00
parent 1598818db6
commit 548d2e4d63
3 changed files with 38 additions and 3 deletions

View File

@@ -16,6 +16,9 @@ limitations under the License.
import i18n from "i18next";
import type { ParseKeys, TFunction } from "i18next/typescript/t";
import type { DefaultNamespace, TOptions } from "i18next/typescript/options";
/**
* An error with messages in both English and the user's preferred language.
*/
@@ -27,8 +30,11 @@ export abstract class TranslatedError extends Error {
*/
public readonly translatedMessage: string;
public constructor(messageKey: string, translationFn: typeof i18n.t) {
super(translationFn(messageKey, { lng: "en-GB" }));
public constructor(
messageKey: ParseKeys<DefaultNamespace, TOptions>,
translationFn: TFunction<DefaultNamespace>,
) {
super(translationFn(messageKey, { lng: "en-GB" } as TOptions));
this.translatedMessage = translationFn(messageKey);
}
}
@@ -38,6 +44,6 @@ class TranslatedErrorImpl extends TranslatedError {}
// i18next-parser can't detect calls to a constructor, so we expose a bare
// function instead
export const translatedError = (
messageKey: string,
messageKey: ParseKeys<DefaultNamespace, TOptions>,
t: typeof i18n.t,
): TranslatedError => new TranslatedErrorImpl(messageKey, t);