Skip to content

Commit e138a1a

Browse files
authored
Add translation type check (#392)
1 parent 65238e2 commit e138a1a

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "reddit-expanded-community-filter-userscript",
3-
"version": "1.4.2",
3+
"version": "1.5.0",
44
"description": "Filter muted communities from /r/all",
55
"keywords": [
66
"reddit",

src/i18n/Localization.ts

+22-5
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,26 @@ import { InternalJSON } from "./@types/InternalJSON";
33
import { mergeDeep } from "../utilities/MergeDeep";
44
import { Translation } from "./@types/Translation";
55

6-
import en from "../../locale/en.internal.json";
7-
import zh from "../../locale/zh.internal.json";
6+
import enRaw from "../../locale/en.internal.json";
7+
import zhRaw from "../../locale/zh.internal.json";
8+
9+
type ReplaceTranslationLocale<T, L> = Omit<T, "locale"> & {locale: L};
10+
11+
/**
12+
* Verify the locale field of a translation, then add that locale literal to the returned type.
13+
* To be replaced by https://github.com/microsoft/TypeScript/issues/32063 in the future.
14+
*/
15+
function verifyTranslation
16+
<T extends Translation<string>, L extends string>(translation: T, expectedLocale: L): ReplaceTranslationLocale<T, L> {
17+
if (translation.locale !== expectedLocale) {
18+
throw new TypeError(`Invalid translation locale: expected "${expectedLocale}" but got "${translation.locale}"`);
19+
}
20+
21+
return translation as Omit<T, "locale"> as ReplaceTranslationLocale<T, L>;
22+
}
23+
24+
const en = verifyTranslation(enRaw, "en");
25+
const zh = verifyTranslation(zhRaw, "zh");
826

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

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

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

0 commit comments

Comments
 (0)