TypeScript makes JavaScript code easier to reason about, but its types disappear at compile time, so they cannot protect a program from the data an attacker actually sends. Many security defects in front-end and server-side JavaScript come from the language itself rather than any framework: dynamic code execution through eval and its relatives, HTML injection sinks in the DOM, prototype pollution through ordinary objects, loose equality and type coercion, and regular expressions that backtrack for minutes. This guide covers those language-level pitfalls, what the TypeScript compiler can and cannot catch, safer patterns for each, how to enforce them with compiler flags, lint rules and browser policies, and how to measure progress. It is written for developers, reviewers and application security engineers working in any JavaScript runtime; framework-specific advice lives in the React and Next.js Security Guide, the Angular Security Guide and the Node.js Security Guide.
Key takeaways
- Types are erased. The TypeScript handbook states that type annotations never change runtime behaviour, and type assertions carry no runtime check, so every value from outside the process needs runtime validation.
- Remove dynamic code execution.
eval,new Functionand string arguments tosetTimeoutandsetIntervalare injection sinks; there is almost always a data-driven alternative. - Write text, not HTML. Use
textContentand DOM construction instead ofinnerHTMLanddocument.write, and enforce it in the browser with Trusted Types. - Do not use plain objects as dictionaries for untrusted keys.
Map,Set,Object.create(null)andObject.hasOwnprevent prototype pollution and object injection. - Make the compiler and linter do the policing.
strict,noUncheckedIndexedAccess,noEmitOnErrorand lint rules banninganyand implied eval turn these rules into build failures.
What TypeScript does and does not protect
TypeScript checks code against declared types and then emits JavaScript with the types removed. That makes it excellent at catching internal mistakes and useless as an input filter.
| Feature | What the compiler guarantees | What happens at runtime |
|---|---|---|
Type annotation (req.body as LoginRequest, function f(id: number)) | Callers inside the codebase pass the declared type | Nothing. An HTTP body, postMessage payload or JSON.parse result can be any shape |
Type assertion (as, <T>) | None; the developer overrides the checker | The handbook notes there is no runtime checking and no exception if the assertion is wrong |
Non-null assertion (value!) | None | Removes null and undefined from the type without checking |
any | Disables further type checking for that value | Errors propagate silently through every property access |
unknown | Forces narrowing before use | Same value, but the code must check it first |
| Emitting with errors | By default tsc still emits JavaScript when there are type errors | Code that failed type checking can ship unless noEmitOnError is set or CI fails on errors |
Validate at every trust boundary
- Type external data as unknown: request bodies, query parameters, headers, cookies,
localStorage,messageevents, WebSocket frames, environment variables and third-party API responses enter asunknown, not as a domain type. - Parse, then trust: run a schema validator (JSON Schema validators or TypeScript-first schema libraries) that rejects unknown properties and returns a typed value only after checks pass. Derive the TypeScript type from the schema so the two cannot drift.
- Allowlist properties: copy the fields an operation needs instead of spreading a request body into a model (
{...req.body}), which is how mass assignment happens. ASVS 5.0 V15.3.3 requires limiting the fields each action may set. - Validate on the server: client-side TypeScript validation is a usability feature. See the Input Validation and Output Encoding Guide.
Dynamic code execution: eval and its relatives
MDN describes eval() as an injection sink: its argument is parsed and executed as JavaScript with the caller's privileges, and direct eval can read and change variables in the surrounding scope. ASVS 5.0 V1.3.2 requires applications to avoid eval() and other dynamic code execution features.
| Dangerous pattern | Why | Safer replacement |
|---|---|---|
eval(str), indirect (0, eval)(str) | Executes arbitrary code; direct eval also exposes local scope | Data structures, lookup tables, a purpose-built expression parser |
new Function(str), AsyncFunction constructor | Parses a string as a function body; still implicit evaluation | Pre-written functions selected from an allowlisted map |
setTimeout("doThing()", 1000), setInterval(str) | String argument is compiled as code | setTimeout(() => doThing(), 1000) |
eval("(" + json + ")") | Executes anything embedded in the "JSON" | JSON.parse(json) followed by schema validation |
eval("obj." + name) | Code injection through the property name | obj[name] only after checking name against an allowlist; MDN warns that unconstrained bracket access enables object injection |
String event handlers (el.setAttribute("onclick", str)) | Compiled as code when the event fires | el.addEventListener("click", handler) |
| Server-side template or VM evaluation of user input | Server-side code execution | Logic-less templates; never treat a VM context as a security sandbox |
Enforce it: a Content Security Policy with script-src or default-src blocks eval by default unless 'unsafe-eval' is present, so keeping 'unsafe-eval' out of the policy turns any remaining eval into a visible error. Where a library genuinely needs evaluation, MDN describes the 'trusted-types-eval' keyword with require-trusted-types-for 'script' as safer than 'unsafe-eval', because it only allows eval where Trusted Types are enforced. In the build, enable ESLint's no-eval, no-implied-eval and no-new-func rules. See the Content Security Policy Guide.
DOM injection sinks and safe rendering
The Trusted Types API documentation groups the dangerous browser APIs into three families. Any untrusted string reaching one of them is a DOM XSS candidate.
| Sink family | Examples | Safe alternative |
|---|---|---|
| HTML sinks | innerHTML, outerHTML, insertAdjacentHTML(), document.write(), DOMParser.parseFromString(), iframe.srcdoc, Range.createContextualFragment() | textContent, createElement plus append; a sanitiser such as DOMPurify only when markup must be rendered |
| JavaScript sinks | eval(), Function(), script.text and script.textContent, string setTimeout, event-handler attributes via setAttribute | Functions and listeners, never strings |
| Script URL sinks | script.src, new Worker(url), importScripts(), serviceWorker.register() | Fixed, same-origin or allowlisted URLs |
| Navigation and URL attributes | location.href = input, a.href, window.open(input) | Parse with new URL() and allow only https: (and known hosts); ASVS 5.0 V1.2.2 asks applications to block javascript: and data: |
- setAttribute is not automatically safe: OWASP's DOM-based XSS cheat sheet notes it is safe only for non-executing attributes such as
title,classandvalue, noton*handlers,hreforsrc. - JSON.stringify is not output encoding: embedding its output in an inline
<script>block can still break out of the script context; serve data as JSON from an endpoint or atype="application/json"element read withtextContent. - Trusted Types: with the CSP directive
require-trusted-types-for 'script', assigning a plain string to a sink throws aTypeError; code must passTrustedHTML,TrustedScriptorTrustedScriptURLobjects created by a named policy, and thetrusted-typesdirective allowlists policy names. MDN lists the API as Baseline 2026, newly available since February 2026, so older browsers may lack it; use a default policy only as a migration aid. See the Trusted Types and DOM XSS Prevention Guide. - DOM clobbering: HTML elements with
idornameattributes can shadow global variables. ASVS 5.0 V3.2.3 asks for explicit declarations, strict type checks and no globals stored ondocument.
See the Cross-Site Scripting (XSS) Prevention Guide for encoding contexts in depth.
Objects, prototypes and dynamic property access
Every ordinary JavaScript object inherits from Object.prototype. Code that merges, clones or assigns properties using keys from untrusted input can write to __proto__, constructor or prototype and change the behaviour of every object in the process. ASVS 5.0 V15.3.6 requires code that prevents prototype pollution, for example by using Set() or Map() instead of object literals.
- Use Map and Set for keyed data: lookups do not touch the prototype chain, which is OWASP's first recommendation in the Prototype Pollution Prevention Cheat Sheet.
- Null-prototype objects: where a plain object is needed, create it with
Object.create(null)so there is no prototype to pollute. - Own-property checks: use
Object.hasOwn(obj, key), which MDN recommends overhasOwnProperty()because it works on null-prototype objects and cannot be overridden; theinoperator also sees inherited properties. - Reject dangerous keys in merge and set-by-path helpers: refuse
__proto__,constructorandprototypeas path segments, and prefer maintained libraries that already do so. - Freeze prototypes as defence in depth:
Object.freeze(Object.prototype)blocks additions, but freezing is shallow and may break libraries that patch built-ins, so test first. On Node.js the--disable-proto=deleteflag removes__proto__, thoughconstructor.prototyperemains reachable. - Left-hand-side input: OWASP warns against untrusted data on the left of an assignment (
window[userInput] = ...); add an allowlist between input and property name.
See the Prototype Pollution Guide.
Equality, coercion and type confusion
JavaScript's loose operators convert types before comparing, and TypeScript's types do not survive to runtime to stop it. ASVS 5.0 V15.3.5 requires explicit type checks and strict equality to avoid type juggling.
| Pitfall | Example of the risk | Pattern |
|---|---|---|
Loose equality == | "0" == 0 and null == undefined are true, so a role or flag comparison can match unexpected input | Always === and !==; enable the eqeqeq lint rule |
| Truthiness checks on security values | if (user.isAdmin) accepts the string "false" from a parsed body | Compare against the exact boolean after schema validation |
| Array where a string was expected | A query string such as ?role=a&role=b becomes an array in many parsers, so role.includes("admin") behaves differently | Validate type as well as value. See the HTTP Parameter Pollution and Parser Differential Guide |
| Object where a primitive was expected | NoSQL operators such as {"$ne": null} passed as a password field | Reject non-string values for string fields before building queries |
| Number precision | IDs above Number.MAX_SAFE_INTEGER lose precision after JSON.parse, so two records can share an ID | Transmit large IDs as strings or use BigInt |
| Unchecked index access | map[key] typed as defined when it may be undefined | Enable noUncheckedIndexedAccess |
Regular expressions and the event loop
Backtracking regex engines, including the default engine in JavaScript runtimes, can take exponential time on crafted input when a pattern contains a repeated group that itself contains repetition or overlapping alternation, such as (a+)+$ or (a|aa)+$, as the OWASP ReDoS description explains. Because JavaScript runs application code on a single event loop, one slow match blocks every other request on a Node.js process and freezes the page in a browser. ASVS 5.0 V1.3.12 requires regular expressions free of exponential backtracking, and V1.2.9 requires escaping metacharacters when user input becomes part of a pattern.
- Never build a pattern from raw input (
new RegExp(userInput)); escape it or use string methods such asincludesandstartsWith. - Bound input length before matching, and anchor patterns.
- Lint for unsafe patterns with a regex-safety rule in CI, and review nested quantifiers by hand.
- Move heavy matching off the main thread to a worker with a timeout where patterns must stay complex.
See the Regular Expression Denial of Service (ReDoS) Guide.
Compiler and lint settings that enforce the rules
| Setting | Effect |
|---|---|
"strict": true | Turns on the strict family, including noImplicitAny, strictNullChecks, strictFunctionTypes, strictPropertyInitialization, useUnknownInCatchVariables and alwaysStrict |
noUncheckedIndexedAccess | Adds undefined to index-signature reads such as process.env.X, forcing a check; not part of strict |
exactOptionalPropertyTypes | Distinguishes an absent property from one set to undefined; not part of strict |
noEmitOnError | Stops tsc emitting JavaScript when type checking fails |
Lint: no-eval, no-implied-eval, no-new-func, eqeqeq | Blocks dynamic code and loose equality |
Lint (typescript-eslint): no-explicit-any, no-unsafe-assignment, no-unsafe-member-access, no-non-null-assertion | Stops any and assertions from leaking unvalidated data |
CSP without 'unsafe-eval' or 'unsafe-inline', plus require-trusted-types-for 'script' | Runtime enforcement in the browser |
Rolling it out
- Measure first: run the linter with the new rules in warning mode and count violations per rule and per package.
- Fix the sinks: remove
evaland string timers, then replace HTML sinks with text APIs or a single sanitising wrapper. - Turn on compiler flags package by package, starting with code that handles requests and messages; add
noEmitOnErrorto the build. - Deploy Trusted Types in report-only mode (
Content-Security-Policy-Report-Only) and collect violation reports before enforcing. - Enforce: make lint rules errors in CI, switch the CSP to enforcing, and keep the report-only header for new code paths. Roll back by reverting the header, not by re-adding
'unsafe-eval'.
Detection and measurement
- CSP and Trusted Types violation reports: collect them centrally; a spike after a release usually means a new sink, and reports from unknown script origins can indicate injection.
- Static analysis findings: track SAST rules for code injection, DOM XSS, prototype pollution and ReDoS by repository. See the SAST Triage Guide.
- Server-side errors: schema validation failures and event-loop lag alerts in Node.js services show both probing and ReDoS attempts.
Metrics:
- Count of
eval,new Functionand string timer calls in first-party code (target zero). - Count of HTML sink assignments outside the approved sanitising wrapper.
- Share of packages compiling with
strictandnoUncheckedIndexedAccess. - Number of
any,ascasts and!assertions at trust boundaries, trending down. - Trusted Types violations per week after enforcement.
- Share of external inputs passing through a schema validator.
Common failure patterns
- Casting the request body:
const input = req.body as CreateUsertreated as validated, so extra fields such asrolereach the database. - One innerHTML for convenience: a notification or rich-text widget writes server data through
innerHTML, and stored content becomes script. - Deep merge of user settings: a home-grown
merge(defaults, userJson)walks__proto__and sets anisAdmindefault on every object. - Regex validation of email or URLs from the internet with nested quantifiers, letting one request stall a Node.js service.
- Secrets in the bundle: API keys placed in front-end environment variables that the bundler inlines, readable in every user's browser. See the Secrets Management Guide.
- Type errors ignored in CI because the build emits anyway, so the strict settings exist only on developer machines.
Framework mapping
| Practice | OWASP ASVS 5.0 | NIST SP 800-53 Rev. 5 | NIST CSF 2.0 |
|---|---|---|---|
| Runtime validation of external input | V2.2.2, V15.3.3 | SI-10 | PR.PS-06 |
| No dynamic code execution | V1.3.2 | SI-10 | PR.PS-06 |
| Safe DOM rendering and URL handling | V3.2.2, V3.2.3, V1.2.2 | SI-10 | PR.PS-06 |
| Prototype pollution prevention | V15.3.6 | SI-10 | PR.PS-06 |
| Strict equality and type checks | V15.3.5 | SI-10 | PR.PS-06 |
| ReDoS-safe regular expressions | V1.3.12, V1.2.9 | SI-10 | PR.PS-06 |
| Compiler, lint and SAST in the pipeline | n/a | SA-11, SA-15 | PR.PS-06 |
For threat modelling, ATT&CK T1059.007 JavaScript covers attacker-run script, and T1189 Drive-by Compromise covers malicious script delivered through compromised pages. ISO/IEC 27001:2022 Annex A control A.8.28 Secure coding is the natural home for these rules.
Practitioner checklist
- All external data is typed as
unknownand validated with a schema before use; noascasts on request bodies or message payloads. - First-party code contains no
eval,new Functionor string timers, and lint rules block new ones. - Untrusted text reaches the DOM only through
textContentor a single reviewed sanitising wrapper. - Trusted Types run in report-only and then enforced mode, with an allowlisted set of policy names.
- CSP omits
'unsafe-eval'and'unsafe-inline'. - Untrusted keys go into
Mapor null-prototype objects; merge helpers reject__proto__,constructorandprototype. - Strict equality is enforced and security flags are compared to exact values.
- Regular expressions are reviewed for nested quantifiers, input length is bounded, and patterns are never built from raw input.
strict,noUncheckedIndexedAccessandnoEmitOnErrorare on, and CI fails on type errors.- No secrets are injected into client bundles.
Standards and references
- OWASP: Application Security Verification Standard 5.0
- OWASP: DOM based XSS Prevention Cheat Sheet
- OWASP: Prototype Pollution Prevention Cheat Sheet
- MDN: eval()
- MDN: Trusted Types API
- TypeScript: Handbook, Everyday Types
- TypeScript: TSConfig Reference
- OWASP: Regular expression Denial of Service (ReDoS)
Related NHI Mgmt Group resources: Trusted Types and DOM XSS Prevention Guide · Prototype Pollution Guide · Client-Side Security Guide · Secure Code Review Guide · Input Validation and Output Encoding Guide