Skip to content

Add translation type check #392

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

Merged
merged 2 commits into from
Oct 26, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "reddit-expanded-community-filter-userscript",
"version": "1.4.2",
"version": "1.5.0",
"description": "Filter muted communities from /r/all",
"keywords": [
"reddit",
Expand Down
27 changes: 22 additions & 5 deletions src/i18n/Localization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,26 @@ import { InternalJSON } from "./@types/InternalJSON";
import { mergeDeep } from "../utilities/MergeDeep";
import { Translation } from "./@types/Translation";

import en from "../../locale/en.internal.json";
import zh from "../../locale/zh.internal.json";
import enRaw from "../../locale/en.internal.json";
import zhRaw from "../../locale/zh.internal.json";

type ReplaceTranslationLocale<T, L> = Omit<T, "locale"> & {locale: L};

/**
* Verify the locale field of a translation, then add that locale literal to the returned type.
* To be replaced by https://github.com/microsoft/TypeScript/issues/32063 in the future.
*/
function verifyTranslation
<T extends Translation<string>, L extends string>(translation: T, expectedLocale: L): ReplaceTranslationLocale<T, L> {
if (translation.locale !== expectedLocale) {
throw new TypeError(`Invalid translation locale: expected "${expectedLocale}" but got "${translation.locale}"`);
}

return translation as Omit<T, "locale"> as ReplaceTranslationLocale<T, L>;
}

const en = verifyTranslation(enRaw, "en");
const zh = verifyTranslation(zhRaw, "zh");

class Localization<TF extends Translation<string>, L extends TF["locale"]> {
static get SINGLETON(): ReturnType<typeof this.loadSingleton> {
Expand All @@ -17,9 +35,8 @@ class Localization<TF extends Translation<string>, L extends TF["locale"]> {

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
private static loadSingleton() {
// Need something like "import as const" so locale is a literal instead of string
return new Localization(en as typeof en & {locale: "en"})
.addTranslation(zh as typeof zh & {locale: "zh"});
return new Localization(en)
.addTranslation(zh);
}

private static singleton: ReturnType<typeof this.loadSingleton> | null = null;
Expand Down