Skip to content

Instantly share code, notes, and snippets.

@Loskir
Last active July 29, 2022 13:43
Show Gist options
  • Save Loskir/a258a2217a185e33e30a3dfdd468c134 to your computer and use it in GitHub Desktop.
Save Loskir/a258a2217a185e33e30a3dfdd468c134 to your computer and use it in GitHub Desktop.
const yaml = require('js-yaml')
const fs = require('fs')
const path = require('path')
function* getDotPaths(data) {
function* iter(obj, parentPaths) {
for (const [k, v] of Object.entries(obj)) {
const p = [...parentPaths, k]
if (typeof v === 'object' && v !== null) {
yield* iter(v, p)
} else {
yield p.join('.')
}
}
}
yield* iter(data, [])
}
const data = yaml.load(fs.readFileSync('./locales/ru.yaml'))
const s = [...getDotPaths(data)]
let content = ''
content += `export declare function t(resourceKey: ${s.map((v) => `'${v}'`).join('|')}, templateData?: Record<string, any>): string\n`
// ↓ function overloading
// for (const v of s) {
// content += `export declare function t(resourceKey: '${v}', templateData?: Record<string, any>): string\n`
// }
// content += `export declare function t(resourceKey: string, templateData?: Record<string, any>): string\n`
const dir = './types/_generated'
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir)
}
fs.writeFileSync(path.join(dir, 'locales.d.ts'), content)
import { t } from './_generated/locales'
import { TelegrafContext } from 'telegraf/typings/context'
declare class I18nContext {
locale(languageCode: string): void
getTemplate(languageCode: string, resourceKey: string): object
t: typeof t
}
declare module 'telegraf' {
export class Context extends TelegrafContext {
i18n: I18nContext
}
}
export interface CustomI18n {
t (languageCode?: string, resourceKey?: Parameters<typeof t>[0], templateData?: object): string;
t (resourceKey?: Parameters<typeof t>[0], templateData?: object): string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment