From: shilangyu Date: Mon, 1 Mar 2021 20:00:43 +0000 (+0100) Subject: Generate typescript i18n types X-Git-Url: http://these/git/%22/display/44b525e5-4101b003e005e70a-d472d963/static/gitweb.css?a=commitdiff_plain;h=19c0223b79d6dbb50afbd19d1779fe35b077ceb2;p=lemmy-ui.git Generate typescript i18n types --- diff --git a/generate_translations.js b/generate_translations.js index 0cab8e3..313e800 100644 --- a/generate_translations.js +++ b/generate_translations.js @@ -1,27 +1,64 @@ -fs = require('fs'); +const fs = require("fs"); -let translationDir = 'lemmy-translations/translations/'; -let outDir = 'src/shared/translations/'; +const translationDir = "lemmy-translations/translations/"; +const outDir = "src/shared/translations/"; fs.mkdirSync(outDir, { recursive: true }); fs.readdir(translationDir, (_err, files) => { files.forEach(filename => { - const lang = filename.split('.')[0]; + const lang = filename.split(".")[0]; try { const json = JSON.parse( - fs.readFileSync(translationDir + filename, 'utf8') + fs.readFileSync(translationDir + filename, "utf8") ); - var data = `export const ${lang} = {\n translation: {`; - for (var key in json) { + let data = `export const ${lang} = {\n translation: {`; + for (const key in json) { if (key in json) { const value = json[key].replace(/"/g, '\\"'); - data = `${data}\n ${key}: "${value}",`; + data += `\n ${key}: "${value}",`; } } - data += '\n },\n};'; - const target = outDir + lang + '.ts'; + data += "\n },\n};"; + const target = outDir + lang + ".ts"; fs.writeFileSync(target, data); } catch (err) { console.error(err); } }); }); + +// generate types for i18n keys +const baseLanguage = "en"; + +fs.readFile(`${translationDir}${baseLanguage}.json`, "utf8", (_, fileStr) => { + const keys = Object.keys(JSON.parse(fileStr)); + + const data = `import * as i18n from "i18next"; + +type I18nKeys = +${keys.map(key => ` | "${key}"`).join("\n")}; + +declare module "i18next" { + export interface TFunction { + // basic usage + < + TResult extends TFunctionResult = string, + TInterpolationMap extends object = StringMap + >( + key: I18nKeys | I18nKeys[], + options?: TOptions | string + ): TResult; + // overloaded usage + < + TResult extends TFunctionResult = string, + TInterpolationMap extends object = StringMap + >( + key: I18nKeys | I18nKeys[], + defaultValue?: string, + options?: TOptions | string + ): TResult; + } +} +`; + + fs.writeFileSync(`${outDir}i18next.d.ts`, data); +});