Types & the Type System
Java is statically typed: every variable has a compile-time type, and the compiler rejects mismatches. TypeScript adds types on top of JavaScript, but the runtime is still the dynamic JS engine. JavaScript itself is dynamically typed: a variable can hold a number now and a string later, and the runtime will happily apply operators to whatever's there (with surprising results).
7 primitive types
string, number, boolean, null, undefined, symbol, bigint β plus one reference type: object. No int/double/long split.
Everything else is object
Arrays, functions, dates, regexes, Map/Set, class instances β all object at runtime.
TS is a compile-time veneer
tsc erases types; the emitted JS is untyped. "Type safety" in TS is a build-time promise, not a runtime guarantee.
Java β JS/TS concept map
| Java | JavaScript / TypeScript | Key difference |
|---|---|---|
int x = 5; long n = 10L; | let x = 5; let n = 10n; | One number type (IEEE-754 double). Integers beyond 2^53 lose precision; bigint opt-in. |
String s = null; | let s = null; let u = undefined; | Two "nothing" values: null (explicit) and undefined (uninitialised). |
List<Integer> list | number[] or Array<number> | Arrays are objects; they can hold mixed types unless TS constrains them. |
Map<K,V> | Map<K, V> | JS Map preserves insertion order, has O(1) get/set, arbitrary keys. Plain object is the trap (see Β§03). |
enum Color { RED } | const Color = { RED: "red" } as const or TS enum | JS has no true enum; TS enum is a compile-time construct with runtime object β prefer as const + union. |
interface / class implements | interface / implements (TS) | JS classes have extends but no interfaces; TS interfaces are structural, not nominal (see Β§09). |
The typeof operator β and its lies
Review trap: typeof x === "object" is true for null, arrays, Dates, and Maps. If a PR uses typeof to distinguish "a real object", it will silently accept null and arrays. The robust checks:
x === null Β· Array.isArray(x) Β· x instanceof Map Β· plain object via Object.prototype.toString.call(x).
TypeScript adds the missing safety β but only at compile time
int add(int a, int b) { return a + b; } // add("x", 2) β compile error
function add(a: number, b: number): number { return a + b; } // add("x", 2) β TS compile error β // at runtime it's just `function add(a, b) { return a+b }` β // types are erased, so a JS caller CAN pass "x" (no guard)
The #1 review mental model: TypeScript cannot protect a runtime boundary. Anything parsed from JSON.parse, req.body, fetch() responses, or an env var is any-or-unknown at runtime even if the TS type says otherwise. A PR that casts req.body as User without validating is lying to the compiler β the object could have anything in it. This is the single most common "deep" review finding.
β Check yourself β Types
1. In a Node API, req.body arrives as JSON. A handler does const u = req.body as User. What's true?
Values, Coercion & Equality
Java lets you write "5" + 3 only with an explicit parse; JavaScript coerces operands automatically. Coercion is where a huge class of PR bugs live β and where reviewers earn their keep.
The equality minefield
Review rule #1: never allow == in new code (except the idiomatic x == null which catches both null and undefined). ESLint's eqeqeq rule exists for exactly this. If you see == in a PR, the author is either new or hiding a coercion bug.
Truthiness β not "false means falsy"
In conditionals, JS converts values to booleans. Falsy values: false, 0, -0, "", null, undefined, NaN, 0n. Everything else β including "0", [], {}, "false" β is truthy.
Review trap: checking if (!user.age) to mean "no age" will also reject 0-year-olds and treat age: "0" as present while age: 0 is absent. When the domain value can legitimately be 0 or "", the guard must be explicit: user.age === undefined || user.age === null.
Number precision β the review classic
- Money / currency in JS: never accumulate floats β use integer cents (or a decimal library). A PR doing
total += price * qtywith dollars is a bug at scale. - IDs as numbers: if a DB returns a 64-bit integer id as
number, it silently loses precision > 2^53. Review call: return as string, or usebigint. - Tolerance comparisons:
Math.abs(a - b) < Number.EPSILONor round to cents β not===on computed floats.
NaN β the only value unequal to itself
Review fingerprint: parseInt / parseFloat / +value on user input, followed by arithmetic β check the PR validates the result is finite (Number.isFinite) before using it.
Data Structures & Mutability
An OO developer's instinct is "objects are like Java references". That instinct mostly holds, but the mutability model and the object-as-map trap will bite.
Primitives are copied; objects are shared (by reference)
List<String> a = new ArrayList<>(); a.add("x"); List<String> b = a; // same object b.add("y"); // a sees it too
const a = ["x"]; const b = a; // same array object b.push("y"); // a is now ["x","y"] too
The immutable-data habit for review: JS passes references everywhere, and a function that mutates its argument ("side effect") surprises callers. Array.prototype.sort() and reverse() mutate in place; map/filter/reduce/slice return new arrays. Object.assign / spread ...obj are shallow clones β nested objects are still shared. A PR that does const copy = {...obj}; copy.items.push(...) thinks it's safe and mutates the original's nested array.
const is not immutability
Review fingerprint: authors who write const everywhere believing it makes state immutable. Object.freeze is shallow and silent; real immutability needs discipline (or immutable libs). When reviewing, check who can mutate shared state rather than whether it was declared const.
Plain object vs Map β the dictionary trap
| You want | Plain object {} | Map |
|---|---|---|
| Arbitrary string keys | β οΈ prototype pollution: key "__proto__", "constructor", "toString" collide with inherited props | β safe |
| Non-string keys (numbers, objects) | β coerced to string (obj[1] and obj["1"] same key) | β any key |
| Insertion order | mostly, but integer-like keys sort first | β guaranteed |
| Count | Object.keys(x).length β O(n) alloc | β
map.size O(1) |
| Iteration | Object.entries() | β
for...of map, map.entries() |
Prototype pollution is a security issue, not just a style one.
obj[userInput] = value where userInput === "__proto__" can mutate the prototype chain β a classic supply-chain/deserialization attack. Reviewers should flag any code that writes into an object using a key derived from untrusted input. Use Map, or Object.create(null), or validate keys against an allow-list.
Destructuring & spread β the modern idioms you'll see everywhere
Default-value nuance: destructuring defaults apply only when the value is undefined β NOT when it's null. const { x = 1 } = { x: null } gives x === null. A PR that assumes "= default catches null" has a latent hole.
The Event Loop β JS's Single-Threaded Concurrency
Java uses threads: multiple call stacks, preemptive scheduling, shared-memory concurrency. JavaScript has ONE thread (per isolate). Concurrency is achieved by interleaving tasks, not running them in parallel. This is both the biggest mental shift and the source of most async bugs you'll review.
The ordering rule that decides every "what prints first?" question
- Run the current call stack to completion.
- Drain the entire microtask queue (all promise reactions).
- Take ONE macrotask (e.g. a timer). Run it. Go back to 2.
Why "setTimeout 0 doesn't run immediately": a timer can only fire when the call stack is empty and all microtasks are done. A slow synchronous loop (while / heavy sync work) blocks the entire event loop β no timers, no I/O, no promise reactions. This is why blocking the event loop is the #1 performance review finding in Node: a synchronous CPU-heavy chunk in a request handler freezes every concurrent request.
Why is Node "single-threaded" yet fast?
- I/O (files, sockets, DB) is asynchronous: while a request awaits a DB query, the loop serves other requests. One thread juggles many in-flight operations (an "event-driven" model, not "one thread per connection").
- The JS thread never waits β it queues the continuation and moves on.
- CPU-heavy work (crypto, compression, native libs) can use a thread pool (
libuv), but the JS code itself stays single-threaded. - For true parallelism:
worker_threads, or the cluster module, or child processes.
Review checklist from this section: β Any synchronous I/O (fs.readFileSync, child_process.execSync, crypto.createHash(...).update(...).digest() big loops) in a request path? β‘ Any unbounded Promise.all or timer soup? β’ Any code assuming order between a promise chain and a timer?
Promises & async/await β The Nuances
A promise is a state machine: pending β fulfilled(value) or rejected(reason). Once settled it never changes. Unlike a Java Future (which you can block on), JS promises are push-based: you register callbacks that run when the value is ready β and you can attach them after settlement too.
The 4 nuances that decide review findings
| Nuance | Reality | Review impact |
|---|---|---|
| Promises are eager | new Promise(exec) runs exec immediately, not when awaited | Creating a promise for a side-effect starts it at creation; a PR that conditionally "awaits" a previously-created promise may have already fired the side effect |
| Chaining creates a NEW promise | p.then(f) returns a fresh promise; p unchanged | Multiple .then on the same promise run independently (fan-out) β not sequentially |
Returning from a .then flattens | return a value β next .then gets it; return a promise β it's awaited (assimilation) | Forgetting to return inside a .then is the most common silent bug β the chain proceeds with undefined and sometimes parallel instead of serial |
Errors you throw inside async/.then become rejections | a thrown exception in an async fn == Promise.reject | Catching-swallowing via empty catch {} hides everything; unmatched catch counts as feature |
async/await is sugar over promise chains β but with a trap
fetchUsers() .then(users => fetchPosts(users[0].id)) .then(posts => posts.length) .then(len => console.log(len)) .catch(err => console.error(err));
async function go() { try { const users = await fetchUsers(); const posts = await fetchPosts(users[0].id); const len = posts.length; console.log(len); } catch (err) { console.error(err); } }
The serialization trap: two awaits in a row run sequentially β the second waits for the first. Parallel-independent awaits are a latency bug (Promise.all fixes it):
const a = await f(); const b = await g(); β total time = time(f) + time(g) β οΈ
const [a, b] = await Promise.all([f(), g()]); β total time = max(f, g) β
The combinator family β pick the right one in review
| Combinator | Behaviour | Fail mode to flag |
|---|---|---|
Promise.all | Waits for ALL; if ANY rejects, the whole thing rejects immediately | One failing request nukes other (already-resolved) results; no partial results on error |
Promise.allSettled | Waits for ALL; never rejects; returns {status, value|reason}[] | The one to use when you want partial success (bulk APIs, fan-out with per-item error handling) |
Promise.race | Settles with the FIRST settled result (value or error) | Timeouts use it: Promise.race([fetch(), timeout(5000)]) β but the loser still runs (side effects!) |
Promise.any | First FULFILLED; rejects only if ALL reject | Great for "try any replica"; errors aggregated (AggregateError) |
Awaiting in loops β microtask-batching traps
Review fingerprints here: β await in a loop that could be Promise.all (latency); β‘ unbounded Promise.all over user-sized arrays (resource exhaustion / rate-limit); β’ using .forEach with async β forEach does NOT await; the promises just fire and errors become unhandled rejections (see Β§06).
β Check yourself β Promises
1. What does this log, in order?
setTimeout(() => console.log(2), 0);
console.log(3);
2. A PR has items.forEach(async (it) => await save(it)) followed by console.log("done"). What's the bug?
Async Error Handling β Where Exceptions Escape
In Java, an exception bubbles up the call stack automatically. In JS, an error thrown inside an async function or a promise callback does not bubble through the call stack β it becomes a rejection that must be handled by another promise's catch. If nothing catches it, you get an unhandledRejection β process warning (and in newer Node, a crash).
The three error-handling shapes, and how to review them
Review rules for async errors
- A promise must be either awaited or caught, eventually. Any
fn()call that returns a promise withoutawait/.catchis a latent unhandled rejection. (Node β₯15 crashes the process by default onunhandledRejectionβ that's a production outage, not a warning.) - Node/Express specifics: an
asyncroute handler that throws does NOT hit the default error middleware automatically (pre-Express 5). A PR addingasync (req,res) => { ... }handlers without a wrapper (asyncHandler/express-async-errors) leaves 500s as unhandled rejections. Classic review finding. - Swallowing is a bug too:
catch (e) {}empty, orcatch { log(e) }then continuing as if success, hides the failure from the caller. Every catch should either rethrow, translate, or return a typed failure β not vanish. - Error types carry shape:
fetchrejects on network error but resolves on HTTP 404/500 β you must checkres.ok. A PR that assumestry { const r = await fetch(url) } catchhandles bad status is wrong;res.okmust be checked. - Timeout hygiene:
AbortController/AbortSignal.timeout(ms)is the modern way; a rawsetTimeout"timeout" that doesn't abort leaves the request in flight forever.
Express 4 vs 5: Express 5 (and 4.20+) propagate async errors to the error middleware automatically; Express 4.19 and below do NOT. When you see async handlers, check which Express is in package.json and whether errors are wrapped. This is both a correctness and a security finding (unhandled rejection can take the process down on Node β₯15).
Prototypes vs Classes β "Classes" Are Sugar
Java classes are compile-time blueprints with inheritance. JS uses prototypal inheritance: every object has a hidden [[Prototype]] link, and property lookup walks the chain. Since ES6, class syntax exists, but it's syntactic sugar over prototypes β there is no real class system, no private-by-default, no true multiple inheritance.
public class Animal { protected String name; public Animal(String name) { this.name = name; } public String speak() { return "..."; } }
class Animal { constructor(name) { this.name = name; } speak() { return "..."; } } // desugars to: Animal.prototype.speak = function... // instances link to Animal.prototype via [[Prototype]]
What this means for reviewers
- "Private" is not a thing by default.
#privateField(ES2022) is real privacy; leading-underscore_fieldis a convention only. A PR relying on underscore "private" is exposing state to any caller. - Method binding: methods are NOT bound to the instance.
const f = obj.methodlosesthis; you needobj.method.bind(obj)or arrow-fieldmethod = () => .... Passing an unbound method (e.g. to an event listener orsetTimeout) is a classicthis === undefinedbug. extendsis prototype-chain sugar:class B extends AsetsB.prototype.[[Prototype]] = A.prototype.super()must be called before touchingthisin a subclass constructor.instanceofwalks the chain βx instanceof Arrayis true for arrays from the same realm only; across realms (iframes, workers, some Node modules) useArray.isArray.- Prototype pollution (again, security): merging untrusted objects into prototypes (
Object.assign(target, userObj)where target could be polluted) enables property injection. Validate keys.
The modern-review stance: most new JS code is written with functions + closures or classes-lite, not deep inheritance hierarchies. Deep class A extends B extends C is often an OO habit ported over and usually a smell in JS β composition (objects holding objects) and small focused modules read better. When reviewing, ask "is the inheritance buying anything, or is it Java habit?"
Scope, this & Closures
Java has block-based lexical scoping too, but JS adds three things that change everything: function hoisting, closures over mutable variables, and a dynamic this (unlike Java's instance-bound this).
The closure-in-loop bug β a review rite of passage
Why it's also a data bug, not just a "loop thing": the same closure-shared-late-binding bites closures over anything captured by reference β a reducer reading a config loaded later, an event handler reading a mutable counter. In review: any callback capturing a var or loop variable, or reading outer mutable state at fire-time instead of capture-time, deserves a comment.
this β dynamic, unless arrow
| Form | What this is |
|---|---|
Regular function function f() {} | Determined by call site: obj.f() β obj; f() β undefined (strict) / global |
obj.f.call(x)/.apply(x)/.bind(x) | Explicitly set |
Arrow function () => {} | Lexical β inherits this from the enclosing scope; cannot be rebound |
| Class method | Same dynamic rules β not auto-bound to the instance (see Β§07) |
Closures are memory-bearing β watch for leaks
- A closure keeps its enclosing variables alive as long as the closure itself is reachable. Event listeners / timers / subscriptions holding references to large objects are a real leak vector in long-running Node processes.
setIntervalholding a closure over a growing array, or a callback registered on a global emitter that keeps the instance alive β reviewers should ask "who releases this?" for every long-lived callback.- Pattern to praise:
setInterval(...); ... clearInterval(...)on shutdown;emitter.removeListener/AbortController.abort()at cleanup.
Modules β CJS vs ESM
Java packages are mostly a namespacing tool. JS modules are a loading, dependency, and execution model β and the language is mid-transition between two incompatible systems. You will review both.
CommonJS (require) β Node's classic
requireis synchronous and cached: the module runs once; everyrequirereuses the same instance. Objects exported are shared β mutating an exported object mutates it for every importer (surprising for Java devs who expect copies).- Circular requires: Node resolves them with partially-initialised modules (the classic trap is requiring a module from its own cycle before it's finished exporting β you get
undefined).
ESM (import/export) β the standard
- ESM is static and async-loaded: imports are hoisted, and the module graph is resolved before any code runs (enables tree-shaking).
- Live bindings:
import { x }reads the current value ofxwhen used, not a snapshot. (Different from CJS's value-at-require.) - Node ESM requires explicit file extensions in relative imports (
"./x.js"β not"./x"); CJS allows extensionless. A PR mixing the two systems (or a CJS package using__dirname/requireinside an ESM file) is a bug to flag β__dirnamedoesn't exist in ESM (useimport.meta.url).
Review fingerprint: "type": "module" in package.json vs require(...) usages; __dirname in an ESM file; module.exports mixed with export; and the dual-package hazard (a package loaded as both CJS and ESM gets two separate instances β instanceof and singleton state break).
TypeScript: Structural Typing & the Safety Model
Java types are nominal: two classes with identical fields are different types unless they share a name / inheritance. TypeScript is structural: any object that shapes like the type is assignable to it. This is the single biggest "wait, that compiles?!" surprise for OO devs.
class Point { int x, y; } class Pixel { int x, y; } Point p = new Pixel(); // β compile error β names differ
interface Point { x: number; y: number } interface Pixel { x: number; y: number } const p: Point = getPixel(); // β compiles if shapes match
What structural typing means in review
- Excess property checking is a lie for variables: assigning a literal object checks for extra properties, but assigning a variable of a wider type does not.
const a: A = {x:1, extra:2}errors;const b = {x:1, extra:2}; const a: A = bcompiles. Reviews should not trust "TS will reject wrong-shaped data" at runtime boundaries. - It enables great minimal interfaces: functions should declare the narrowest shape they need (
{ id: string }), letting any wider object in. That's idiomatic and good β but only when the caller actually has the fields (see runtime-validation rule Β§01). - Discriminated unions are the flagship pattern (see Β§11) β replacing Java's
instanceof-tree with a singlekind/typefield and exhaustive narrowing.
any, unknown, never β the power trio
| Type | Meaning | Review stance |
|---|---|---|
any | Opt out of checking entirely β assignable to/from everything | π΄ Flag. any spreads: a variable typed any voids the safety of everything it touches. Exceptions: legacy interop, truly dynamic data you validate immediately after. |
unknown | "I don't know" β must narrow before use | β
Prefer at boundaries: JSON.parse β unknown, then validate/narrow to a real type. Forces the runtime check TS can't do. |
never | Uninhabited β no value has this type | β
Harness for exhaustiveness: the final else/default branch typed never fails to compile if someone adds a union member and forgets it. Reviewers love seeing it. |
Review rules that matter more than style: β strict: true in tsconfig is non-negotiable for new code (strictNullChecks alone eliminates the most common JS crash: reading a property of undefined). β‘ Disallow as casts on unvalidated runtime data. β’ Watch for @ts-ignore / any sprinkled to "make it compile" β each is a hole. β£ as any is almost always a bug signal, not a workaround.
interface vs type β and what changes for review
interface | type alias | |
|---|---|---|
| Mergeable | β declaration merging (augment) | β no |
| Unions / intersections / primitives / mapped types | β no | β yes |
| Extends | interface B extends A | type B = A & {...} |
| Performance edge | slightly faster to typecheck (cache) | marginal |
Rule of thumb you'll see in guides and should echo in reviews: use interface for public object shapes you'll extend or merge; use type for unions, intersections, tuples, and computed types. Either works 95% of the time β consistency matters more than the choice.
TypeScript: Advanced Patterns You'll Actually See
Discriminated unions + exhaustiveness β the review gold standard
Why reviewers love this: it's the type-safe replacement for Java's exception-trees/instanceof-chains, it makes invalid states unrepresentable (a Result can't be both ok and err), and the never default catches future drift at compile time. Praise it when you see it; suggest it when a PR uses boolean flags or parallel arrays to model alternatives.
Type narrowing β the "smart" checks
Generics β constraint + infer
Utility types to know before reviewing: Partial<T>, Required<T>, Readonly<T>, Pick<T,K>, Omit<T,K>, Record<K,V>, ReturnType<F>, Awaited<T>, NonNullable<T>, Exclude/Extract, Parameters<F>. A PR using any where Pick/Omit/Record fits is missing the point.
satisfies, as const, and enum β three things to check
as constturns a literal object into readonly literal types β the idiomatic "enum substitute":const Roles = { ADMIN: "admin", USER: "user" } as constgives youtype Role = (typeof Roles)[keyof typeof Roles].satisfieschecks a value against a type without widening it:const cfg = {...} satisfies Configkeeps the literal types while verifying the shape.- TS
enumis a runtime object with reverse mappings and is a source of "enum vs union" debates; numeric enums especially can be a footgun. In review: preferas const+ union unless the codebase standardises on enums.
JS/TS Code Review Playbook
Now the part you actually asked for: where to look, in what order, and how to phrase feedback with depth. The drills below are built from the exact bug classes in this primer β subtle enough that they routinely ship merged.
The reviewer's rubric for JS/TS
| Lens | Ask yourself |
|---|---|
| Runtime boundaries | Anything parsed (JSON, req.body, env vars, fetch responses, DB rows) validated before use? Any as T cast on unvalidated data? any leaking? |
| Async correctness | Every promise awaited or caught? Async in forEach? Serial awaits that should be Promise.all? Unbounded parallelism? unhandledRejection risk? |
| Error handling | Empty/vanishing catches? res.ok checked after fetch? Express async handlers wrapped? Errors leaking internals to clients? |
| Data semantics | == anywhere? Truthiness used where 0/"" are valid? Float money math? 2^53 ids as numbers? sort() mutating shared arrays? Shallow-clone-treated-as-deep? |
| State & scope | Closures capturing loop vars/late-bound state? Unbound methods losing this? Listeners/timers never cleaned up? Module-level mutable state shared across requests? |
| Security surface | Prototype pollution from untrusted keys? Secrets in logs/env committed? Input length limits? Regex DoS (ReDoS) on user input? PII in logs? |
| TypeScript honesty | Does the type system prove the claim, or are the seams papered with any/@ts-ignore/as? Exhaustive switches? strict on? |
| Systemic | Sync I/O on the event loop? Module-system confusion (CJS/ESM)? Node version assumptions? Dependency with known CVEs (npm audit)? Over-broad dependency (lodash for one fn)? |
How to use the drills: read the snippet, form your own hypothesis before answering, then check. The analysis goes deeper than the multiple-choice β root cause β blast radius β concrete fix β the exact phrasing to use in review.
Parallel awaits, serialized
asyncContext: An Express handler that enriches a user record before responding.
What's the real issue, aside from style?
Root cause
Confusing "async = automatic concurrency" with "await = I'm waiting, but the loop can go do other requests". await suspends THIS function; it does not run other awaits in parallel.
Blast radius
- Latency: total = t_user + t_posts + t_subs; correct = t_user + max(t_posts, t_subs).
- At scale: longer-held DB connections per request β fewer concurrent requests served β queueing.
- Easier to miss when the calls are hidden inside helpers:
await a(); await b()in different lines reads innocent.
Fix pattern
Parallelism is explicit in JS β reviewers should treat adjacent independent awaits as a finding, not a nit, when latency matters.
The async handler with no catch
reliabilityContext: Express 4 app. New endpoint added with an async handler.
The DB write fails. What actually happens?
Root cause
Express 4's handler contract is synchronous. An async handler returns a Promise the framework ignores; rejection = unhandled.
Blast radius
- Client hangs (no response) β LB timeout β retry storms.
- Node β₯15 default: crash on unhandledRejection β whole process, all users.
- Errors invisible in logs (no middleware ran) β hard to diagnose.
Fix pattern
The truthiness gate that eats zero
data semanticsContext: A session/cost API. Each session has a budgetUsd that may legitimately be 0 (free tier, test tenant).
What breaks?
Root cause
Using truthiness as a presence check. if (!x) means "x is falsy" β which includes 0, "", NaN, false β not "x is absent".
Blast radius
- Free-tier tenants (0 budget) blocked; empty-string configs treated as defaults; falsy-but-valid flags flipped.
- Usually discovered in prod by a specific class of user β 0-count, 0-price, ""-value β i.e. exactly the users with the most sensitive edge cases.
Fix pattern
The shallow copy that mutated the original
data integrityContext: An in-memory cache + audit helper.
The caller's cached object β what changed?
Root cause
Shallow-copy semantics mistaken for deep-copy. Applies to Object.assign and spread alike; also applies to JSON.parse(JSON.stringify(x)) in reverse (deep but drops functions/Date/undefined and can throw on cycles).
Blast radius
- Cache corruption: the "copy path" writes into the shared cached object β every subsequent read sees the mutation.
- Hard to spot: the bug lives in a helper far from both call sites.
- Multi-request shared state (module-level cache) makes it a concurrency-visible bug: one request's transform leaks into another's view.
Fix pattern
Typed lie at the API boundary
TypeScript honestyContext: TypeScript service; request body handled without validation.
What's the right review call?
Root cause
Treating the type system as a runtime validation layer. TS erases types; req.body is whatever the client sent.
Blast radius
- NaN stored to DB (bad data at rest), 500s on missing fields, and β worse β security checks gated on typed-but-unvalidated fields (e.g.
rolecast toAdminRole) can be bypassed with crafted JSON. - The compile-time ecosystem gives false confidence; the bug class is identical to "magic from JSON in Java without parsing".
Fix pattern
sort() mutating shared state
data integrityContext: A list endpoint reused per request; results cached in a module-level array.
What's the hidden consequence?
Root cause
Thinking sort returns a new array (like map). It mutates + returns the same reference.
Blast radius
- One request's sort option permanently changes the cached ordering for all users β subtle, data-dependent, near-impossible to reproduce deterministically.
- Same class:
reverse(),splice(),push/pop/shift/unshift,fill(), and object mutation via helpers.
Fix pattern
Glossary β the terms reviewers actually use
Implicit type conversion when operators meet mismatched types ("5" + 3 β "53", "5" - 3 β 2). The + operator concatenates if either operand is a string; other arithmetic operators convert to numbers.
Values that coerce to false/true in boolean contexts. Falsy: false, 0, -0, "", null, undefined, NaN, 0n.
The single-threaded scheduling loop that interleaves synchronous code, microtasks (promise reactions) and macrotasks (timers, I/O). Order: call-stack β all microtasks β one macrotask β repeat.
Microtasks (promise callbacks, queueMicrotask) drain before macrotasks (setTimeout/setInterval, I/O). Why Promise.resolve().then(...) beats setTimeout(0).
A promise settled with a reason (error). Not an exception; it's a value flowing down the chain. Unhandled rejections crash modern Node.
A rejected promise with no .catch/await. Node β₯15 exits by default β a production outage vector.
The hidden link objects use for property resolution. Class extends sets it; hasOwnProperty distinguishes own vs inherited.
A function retaining access to its enclosing scope's variables after that scope exits. The mechanism behind callbacks, and the source of capture-vs-reference bugs.
var and function declarations are moved to the top of their scope. var is function-scoped and hoisted-but-undefined; let/const are block-scoped with a temporal dead zone. Why "always use let/const".
The window where a let/const binding exists but isn't initialised β accessing it throws ReferenceError.
Shallow (spread, Object.assign) copies top-level references; deep (structuredClone, JSON round-trip with caveats) copies nested values.
Writing into __proto__/constructor.prototype via untrusted keys can modify the shared prototype chain β a security vulnerability class.
"use strict" (or ESM/modules, which are always strict) β disables sloppy-mode footguns (silent failures become throws, this in plain calls is undefined).
TypeScript's rule: assignability by shape, not name. Enables minimal interfaces; requires runtime validation at real boundaries.
TS refining a union to a specific member inside a branch (typeof, instanceof, in, discriminated kind, type guards).
A union of object types sharing a literal tag field (kind); narrowing on the tag gives exhaustive, type-safe alternatives.
satisfiesTS operator that checks a value against a type without widening the literal types β "shapes like, but stays precise".
as constMarks a literal as readonly and gives literal types β the idiomatic enum replacement.
Two module systems: require/module.exports (synchronous, cached, Node-classic) vs import/export (static, async, standard). Mixing them breaks __dirname, require, and can duplicate module state.
Bundlers dropping unused exports at build time β enabled by ESM's static analysis. Why "import { chunk } from 'lodash-es'" beats importing the whole lodash.
The modern way to cancel fetch and timeouts; AbortSignal.timeout(ms) is a one-liner timeout that actually aborts the request.
"Not a Number" β result of failed numeric coercion. The only value !== itself; check with Number.isNaN.
Regular-expression denial of service: a catastrophic-backtracking regex run over user input can lock the single event loop thread. Review user-input regexes for nested quantifiers.