XSS Prevention 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
- ✓XSS Prevention runs in O(n) time and O(n) space, in TypeScript as in every other language.
- ✓The runtime is JavaScript, so the escaping calls are identical; what TypeScript adds is a branded or opaque type.
- ✓Reviewers look for the escape module being the sole producer of the branded type, and for zero as-casts anywhere near it, since one cast reopens the whole hole.
- ✓The TypeScript trap: Types are erased before the sink runs, so a declaration that says innerHTML takes TrustedHTML compiles happily and enforces nothing at runtime.
- ✓Branding is compile-time only: a branded string is the same string, so the safety costs zero bytes and zero allocations.
What XSS Prevention actually is
XSS Prevention in TypeScript: what you actually reach for
TypeScript implementation
declare const brand: unique symbol;
export type SafeHtml = string & { readonly [brand]: "SafeHtml" };
const MAP: Record<string, string> = {
"&": "&", "<": "<", ">": ">", '"': """, "'": "'",
};
export const escapeHtml = (s: string): SafeHtml =>
s.replace(/[&<>"']/g, (c) => MAP[c]!) as SafeHtml;
// The only sink in the codebase. A raw string cannot reach it.
export function setHtml(el: Element, html: SafeHtml): void {
el.innerHTML = html;
}
// req.query is string | string[] | ParsedQs, NOT string: ?name[x]=1 yields an
// object at runtime, and String(obj) is "[object Object]", so an escaper
// typed against string silently never sees the payload aimed at it.
function asText(v: unknown): string {
return typeof v === "string" ? v : "";
}
setHtml(el, escapeHtml(asText(req.query.name)));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 XSS Prevention?
The runtime is JavaScript, so the escaping calls are identical; what TypeScript adds is a branded or opaque type. Declare type SafeHtml = string & { readonly [brand]: 'SafeHtml' } using a unique symbol, make escapeHtml the only function that produces one, and type every sink to accept SafeHtml alone. @types/trusted-types supplies TrustedHTML for the same trick at the DOM boundary, and React types dangerouslySetInnerHTML as an object with a __html string, which is exactly the field to narrow to your own branded type.
What is the most common TypeScript mistake when implementing XSS Prevention?
Types are erased before the sink runs, so a declaration that says innerHTML takes TrustedHTML compiles happily and enforces nothing at runtime. The concrete bite is the request boundary: Express types req.query values as string, string array or a parsed object, because a repeated key yields an array and a bracketed key yields an object, so a handler annotated as taking a string can receive an object at runtime. String(object) then hands your escaper the harmless text [object Object] while the real payload arrives somewhere you never escaped. A declared interface for a fetch body is a comment, not a check.
How does XSS Prevention actually perform in TypeScript?
Branding is compile-time only: a branded string is the same string, so the safety costs zero bytes and zero allocations. That is why it beats a runtime wrapper class, which allocates one object per escaped value and survives erasure only by paying for it every time. The escape itself is one regex replace with a character class and a callback, scanning the string once, which is measurably cheaper than five chained replace calls that each allocate an intermediate. Nothing here changes the emitted JavaScript, so profiles look identical to hand-written JS. 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? Student discounts on developer tools are collected on Noizz, tool by tool.
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.