Template Engine Implementation in TypeScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Template Engine runs in O(n) time and O(n) space, in TypeScript as in every other language.
- ✓TypeScript contributes no runtime library, so the interesting surface is the checker. Template literal types with `infer` pull placeholder names out of the template string itself; a `declare const` of `unique symbol` type gives you an unforgeable brand for encoded output; `as const` preserves the literal type through a variable; `satisfies` checks a context object without widening it.
- ✓Brand, do not alias. `type SafeHtml = string` is a comment with syntax; `string & { readonly [HTML]: true }` backed by a module-private `unique symbol` cannot be produced outside the module that owns the escaper.
- ✓The TypeScript trap: The recursion that makes this pleasant has a ceiling. A `Vars<S>` type peeling one `{{...}}` per instantiation stops at roughly fifty placeholders, where tsc reports TS2589, 'Type instantiation is excessively deep and possibly infinite' (measured on 5.5 with the exact shape below).
- ✓Run-time cost is exactly the JavaScript version's; the bill arrives at build time. Every `{{...}}` peel is a fresh type instantiation, and `tsc --diagnostics` prints the running total: the file below reports about 4,200 instantiations and 0.9 seconds of check time on its own, which is fine until the same `Vars` is applied across a few hundred templates and editor latency collapses.
What Template Engine actually is
Template Engine in TypeScript: what you actually reach for
TypeScript implementation
declare const HTML: unique symbol;
/** Nominal brand: erased at runtime, unforgeable inside the module. */
export type SafeHtml = string & { readonly [HTML]: true };
type Trim<S extends string> = S extends ` ${infer R}` ? Trim<R>
: S extends `${infer R} ` ? Trim<R> : S;
/** Placeholder names lifted out of the literal at type-check time. */
export type Vars<S extends string> =
S extends `${string}{{${infer Hole}}}${infer Rest}` ? Trim<Hole> | Vars<Rest> : never;
const ENTITY: Record<string, string> = { "&": "&", "<": "<", ">": ">", '"': """ };
const esc = (v: string): SafeHtml =>
v.replace(/[&<>"]/g, (c) => ENTITY[c]!) as SafeHtml;
export const raw = (v: string): SafeHtml => v as SafeHtml;
type Step = (d: Record<string, string>, out: string[]) => void;
const CACHE = new Map<string, readonly Step[]>();
function compile(tpl: string): readonly Step[] {
const steps: Step[] = [];
for (const part of tpl.split(/(\{\{[^}]*\}\})/g)) {
if (part.startsWith("{{")) {
const key = part.slice(2, -2).trim();
steps.push((d, out) => out.push(esc(d[key] ?? "")));
} else if (part) { steps.push((_d, out) => out.push(part)); }
}
return steps;
}
export function render<S extends string>(tpl: S, data: Record<Vars<S>, string>): SafeHtml {
let steps = CACHE.get(tpl);
if (!steps) CACHE.set(tpl, (steps = compile(tpl)));
const out: string[] = [];
for (const s of steps) s(data as Record<string, string>, out);
return out.join("") as SafeHtml;
}
const ROW = "<td>{{platform}}</td><td>{{ note }}</td>" as const;
render(ROW, { platform: "4B", note: 'delayed <20" min>' });
// @ts-expect-error 'note' is required by Vars<typeof ROW>
render(ROW, { platform: "4B" });Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Template Engine?
TypeScript contributes no runtime library, so the interesting surface is the checker. Template literal types with `infer` pull placeholder names out of the template string itself; a `declare const` of `unique symbol` type gives you an unforgeable brand for encoded output; `as const` preserves the literal type through a variable; `satisfies` checks a context object without widening it. `Record<Vars<S>, string>` then turns a forgotten value into a compile error at the call site. At run time you are still shipping the JavaScript underneath: a `Map`, an array of closures, and `join`.
What is the most common TypeScript mistake when implementing Template Engine?
The recursion that makes this pleasant has a ceiling. A `Vars<S>` type peeling one `{{...}}` per instantiation stops at roughly fifty placeholders, where tsc reports TS2589, 'Type instantiation is excessively deep and possibly infinite' (measured on 5.5 with the exact shape below). There is no partial result: the type collapses to `never`, `Record<never, string>` accepts any object, and every call site silently loses its checking. The other half is erasure. The brand lives only in the checker, so a value typed `any` out of `JSON.parse` satisfies `SafeHtml` without one character being encoded.
How does Template Engine actually perform in TypeScript?
Run-time cost is exactly the JavaScript version's; the bill arrives at build time. Every `{{...}}` peel is a fresh type instantiation, and `tsc --diagnostics` prints the running total: the file below reports about 4,200 instantiations and 0.9 seconds of check time on its own, which is fine until the same `Vars` is applied across a few hundred templates and editor latency collapses. Keep the recursive type behind an opt-in helper rather than the default signature, and cache the compiled step array in a plain `Map` so the emitted JavaScript carries none of the type-level machinery. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Devin free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.