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
No known key found for this signature in database
GPG Key ID: A2B008A5F49F5D0D
3 changed files with 38 additions and 3 deletions

28
src/@types/i18next.d.ts vendored Normal file
View File

@ -0,0 +1,28 @@
/*
Copyright 2023 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import "i18next";
// import all namespaces (for the default language, only)
import app from "../../public/locales/en-GB/app.json";
declare module "i18next" {
interface CustomTypeOptions {
defaultNS: "app";
resources: {
app: typeof app;
};
}
}

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);

View File

@ -14,6 +14,7 @@
"noUnusedLocals": true,
"moduleResolution": "node",
"declaration": true,
"resolveJsonModule": true,
// TODO: Enable the following options later.
// "forceConsistentCasingInFileNames": true,