Skip to content

Instantly share code, notes, and snippets.

@jspears
Created October 17, 2023 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jspears/91a48e587287fc09e59eade255e5b408 to your computer and use it in GitHub Desktop.
Save jspears/91a48e587287fc09e59eade255e5b408 to your computer and use it in GitHub Desktop.
A little template language

Playground

type Trim<S> = S extends (` ${infer V}` | `${infer V} ` |`${infer V}`) ? V : never;

type Templ<S> = S extends `${string}{{${infer Prop extends string}}}${infer Right}` ? {[k in Trim<Prop>]: string} & Templ<Right> : {};

function templ<T extends string, V = Templ<T>>(str:T, sub:V){
    return str.replaceAll(/{{\s*(.+?)\s*}}/g, (a,prop)=>sub[prop] ?? '' );
}

const s = templ(`hello {{ name }} nice to {{greet}} you`, {name:'Bob', greet:'meet'})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment