@@ -3,8 +3,26 @@ import { InternalJSON } from "./@types/InternalJSON";
3
3
import { mergeDeep } from "../utilities/MergeDeep" ;
4
4
import { Translation } from "./@types/Translation" ;
5
5
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" ) ;
8
26
9
27
class Localization < TF extends Translation < string > , L extends TF [ "locale" ] > {
10
28
static get SINGLETON ( ) : ReturnType < typeof this . loadSingleton > {
@@ -17,9 +35,8 @@ class Localization<TF extends Translation<string>, L extends TF["locale"]> {
17
35
18
36
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
19
37
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 ) ;
23
40
}
24
41
25
42
private static singleton : ReturnType < typeof this . loadSingleton > | null = null ;
0 commit comments