const templates = { 'my-template': { converter: (context?: number[]) => { return context?.join(', ') || ''; }, }, } as const; type Template = typeof templates; type TemplateName = keyof Template; type TemplateContext = { [key in TemplateName]: Parameters[0]; }; export function convertTemplate( text: string, context?: TemplateContext, templateUse?: TemplateName[], ) { let ret = text; for (const [name, template] of Object.entries(templates)) { if (templateUse && !templateUse.includes(name as TemplateName)) continue; ret = text.replace( new RegExp('\\#\\[' + name.replaceAll('-', '\\-') + '\\]', 'g'), typeof template.converter === 'function' ? template.converter(context?.[name as TemplateName]) : template.converter, ); } return ret; }