Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Tiny Typescript string template compiler
// makes use of tagged template literals
const compileTemplate = (strings: TemplateStringsArray, ...expr: string[]) => {
return (replacements: Record<string, any>) => {
// convert ${'whatever'} instances to array of values
const values = expr.map(key => replacements[key] ?? key);
// rebuild string with replaced values
return strings.reduce((result, part, i) => result + part + (values[i] ?? ''), '');
}
}
// Usage
const template = compileTemplate`this is a ${'thing'}`;
const formatted = template({ thing: 'pen' });
// formatted === 'this is a pen'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment