]> Untitled Git - lemmy-ui.git/blob - generate_translations.js
Improve type safety
[lemmy-ui.git] / generate_translations.js
1 const fs = require("fs");
2
3 const translationDir = "lemmy-translations/translations/";
4 const outDir = "src/shared/translations/";
5 fs.mkdirSync(outDir, { recursive: true });
6 fs.readdir(translationDir, (_err, files) => {
7   files.forEach(filename => {
8     const lang = filename.split(".")[0];
9     try {
10       const json = JSON.parse(
11         fs.readFileSync(translationDir + filename, "utf8")
12       );
13       let data = `export const ${lang} = {\n  translation: {`;
14       for (const key in json) {
15         if (key in json) {
16           const value = json[key].replace(/"/g, '\\"');
17           data += `\n    ${key}: "${value}",`;
18         }
19       }
20       data += "\n  },\n};";
21       const target = outDir + lang + ".ts";
22       fs.writeFileSync(target, data);
23     } catch (err) {
24       console.error(err);
25     }
26   });
27 });
28
29 // generate types for i18n keys
30 const baseLanguage = "en";
31
32 fs.readFile(`${translationDir}${baseLanguage}.json`, "utf8", (_, fileStr) => {
33   const keys = Object.keys(JSON.parse(fileStr));
34
35   const data = `import { i18n } from "i18next";
36
37 declare module "i18next" {
38   export type I18nKeys = 
39 ${keys.map(key => `    | "${key}"`).join("\n")};
40   
41   export interface TFunctionTyped {
42     // basic usage
43     <
44       TResult extends TFunctionResult = string,
45       TInterpolationMap extends Record<string, unknown> = StringMap
46     >(
47       key: I18nKeys | I18nKeys[],
48       options?: TOptions<TInterpolationMap> | string
49     ): TResult;
50     // overloaded usage
51     <
52       TResult extends TFunctionResult = string,
53       TInterpolationMap extends Record<string, unknown> = StringMap
54     >(
55       key: I18nKeys | I18nKeys[],
56       defaultValue?: string,
57       options?: TOptions<TInterpolationMap> | string
58     ): TResult;
59   }
60
61   export interface i18nTyped extends i18n {
62     t: TFunctionTyped;
63   }
64 }
65 `;
66
67   fs.writeFileSync(`${outDir}i18next.d.ts`, data);
68 });