Keep Narrowed Types In Closures With const
Show why TypeScript resets narrowing on mutable let bindings inside callbacks, and preserve narrowed types by capturing a const snapshot before deferral.
Show why TypeScript resets narrowing on mutable let bindings inside callbacks, and preserve narrowed types by capturing a const snapshot before deferral.
Destructure discriminated union fields into const bindings before branching so TypeScript still narrows payload types inside switch and if statements.
Enforce exact object shapes on aliased variables in generic functions with Record<Exclude<keyof Input, keyof Shape>, never> so typos fail at compile time.
Generate exact-arity tuple types with a recursive FixedTuple<T, N> alias and pair it with a runtime length guard for RGB vectors and byte blocks.
Pair Intl.PluralRules ordinal selection with a typed lookup table requiring an other fallback so rank formatting handles 1st, 2nd, 3rd, and 11th accurately.
Narrow Map values safely by assigning map.get(key) to a local binding instead of calling map.has(key) first, avoiding non-null assertions in strict TypeScript.
Strip the explicit this parameter from bound method types with OmitThisParameter so callback registries accept standalone functions without receiver errors.
Constrain generic indexers with PropertyKey so helpers preserve string, numeric status code, and unique symbol keys instead of widening keys to string.
Expose ReadonlySet views across module boundaries to hide add, delete, and clear from callers while preserving lookup, iteration, and element covariance.
Distinguish {}, object, and Record<PropertyKey, never> in TypeScript: only PropertyKey mapped to never blocks both primitives and extra object properties.
Build a mapped union helper RequireAtLeastOne<T, K> so callers must supply at least one optional identifier key while rejecting empty objects at compile time.
Separate RequiredKeys<T> and OptionalKeys<T> using conditional mapped types over Pick<T, K>, then validate mandatory keys before merging config defaults.
Refine string[] output from String.prototype.split into a fixed-length tuple using a custom type guard so positional destructuring stays strictly typed.
Combine ordered predicates and type guards inside switch (true) to narrow union events and numeric thresholds without deeply nested if-else chains.
Return a this is NarrowedState predicate from class methods so conditional checks narrow the receiver instance itself without external guard helpers.
Type variadic prefixes and packet interiors with leading and middle rest elements in labeled tuples so fixed header and trailing targets stay strongly typed.
Chain data transformations left to right with typed function overloads so each stage infers its parameter from the previous return value without any.
flat(1) only unwraps one array level and the compiler tracks it: flat(2) and flat(Infinity) return deeper element unions, so type errors surface wrong depths.
The details toggle event arrives as a plain Event, so handlers cast to ToggleEvent once and read newState, oldState, and the open flag with full types.
Intl.NumberFormat renders currency per locale and formatToParts splits the result into typed parts, so symbol, integer, and fraction render separately.
Chained Object.assign calls give the result an intersection of every source type, so a later patch with different field shapes widens reads instead of erroring.
Object.keys returns string for typed objects, so a cast restores the union; Object.entries pairs each key with its value type for typed rebuilds.
A Record keyed by a role union forces every entry to exist, so reading table[role] never returns undefined and capability checks need no runtime fallback.
HTMLInputElement.setRangeText replaces a character range with four selection modes, and omitting start and end targets the current user selection instead.
Array.from with a fill(0) inner call gives each matrix row an independent array, while copyWithin moves values inside one array in place with typed bounds.
findLast and findLastIndex search backwards through readonly arrays and return undefined or -1 when nothing matches, typed as T | undefined at the call site.
formatToParts yields Intl.DateTimeFormatPart objects that narrow on part.type, and resolvedOptions reports the exact locale, calendar, and hour cycle chosen.
Spreading map.entries() yields typed tuple arrays that sort and filter like normal arrays, and new Map(entries) rebuilds with insertion order restored.
Object.freeze pairs with Readonly type annotations so runtime writes throw TypeError while compile-time index writes fail before the build.
queueMicrotask callbacks run after the current task in FIFO order interleaved with promise reactions, so all microtasks drain before any timer fires.
splice returns the removed elements as a typed array, deletes or replaces in place, and index beyond length is a silent no-op on an empty result.
toSorted returns a new sorted array and accepts readonly inputs, so ranking views never reorder the source and nested tuples stay fully typed.
Array.prototype.with returns a copy with one index replaced, accepts negative indices, throws RangeError beyond length, and keeps the source untouched.
Inline handlers get parameter types from context; extracting one into a variable loses that context, leaving an implicit any until you annotate it.
document.fonts.load requests the faces for glyphs about to render and resolves with FontFace[], so icons draw only after the family is really available.
Global key handlers fire for every focused window, so document.hasFocus() gates shortcuts and stops a page from consuming keystrokes another window owns.
form.reset() restores controls natively but custom UI state is yours; the reset event runs before the revert, so deferred reads see the restored values.
inputMode picks the virtual keyboard layout and enterKeyHint labels the action key, taming mobile form fields without changing the input type.
The invalid event fires per failing control and does not bubble, so a form-level listener uses capture to route validationMessage into field slots.
Repeated DOM edits leave adjacent text nodes where the reader sees one string; normalize() merges them and drops empty ones so ranges see a single node.
pageshow fires on every load and on back-forward cache restores; persisted means timers and sockets were frozen, so live subscriptions must be re-established.
Relative selectors passed to element.querySelector still run against the whole document; prefixing :scope anchors them to the element the query was called on.
The selectionchange event fires on the document for every caret move, so the active element decides whose selectionStart the toolbar should read.
attachShadow with delegatesFocus sends host focus to the first focusable node in the shadow root, and focus events retarget to the host for outside listeners.
strictFunctionTypes checks property-signature callbacks contravariantly while method shorthand stays bivariant, so narrow params slip through methods.
Hoist a discriminant check into a const boolean once and every later branch inherits the narrowing — no repeated event.kind comparisons.
Gate a staged startup behind a one-shot barrier: each service connects at its own speed and every continuation resumes only after all parties arrive.
Try mirrors in order and keep the first success: failures accumulate into an attempts report, so a final miss lists every reason.
Wire beforeunload to unsaved form state so the browser asks before discarding edits, using preventDefault plus returnValue per current guidance.
ES2022 class fields create own properties — TypeScript rejects a subclass field over a base accessor (TS2610), so route writes through assignments instead.
Dismiss a popover on outside clicks by asking popover.contains(target) instead of re-querying the DOM, keeping trigger clicks inside the guard.
Read event.composedPath to recover the real shadow-DOM propagation path when retargeting makes event.target report the host element instead.
const preserves literal types but let widens them to string, so union-typed parameters reject the widened value until an annotation stops the widening.
Open a custom menu at the pointer, then clamp its box with Math.min and Math.max so it never spills past the viewport edges.
Type document.createElement through the tag-name map: canvas, a, and tr return their specific element interfaces while unknown tags stay HTMLElement.
Create SVG nodes with createElementNS so the tag-name map returns SVGRectElement and SVGCircleElement directly, making attribute APIs type-check without casts.
Type the payload once with CustomEvent<T> so dispatch and listeners share the same detail shape, then destructure fields without manual checks.
Gate rendering on document.fonts.ready, request specific faces with fonts.load, and probe availability synchronously with fonts.check.
Direct casts between shapes with no overlap fail with TS2352; routing through unknown works, but a real guard beats a double assertion.
Reorder list items with native drag events: draggable rows, a dragover preventDefault to allow drops, and a drop handler that moves the task in place.
Let a custom element join form validation by attaching ElementInternals: set the submitted value and drive checkValidity with setValidity.
Model absent versus explicitly undefined option fields: under exactOptionalPropertyTypes an optional property rejects undefined unless the union allows it.
Call focus({ preventScroll: true }) for keyboard navigation so focus moves between panes without scrolling the viewport away from the reader.
Pass an object with a handleEvent method to addEventListener: this binds to the listener instance and one object can serve many elements.
Await img.decode() before revealing an image so the DOM swap happens only when the bitmap is paint-ready, with a fallback when decoding fails.
Open a date input's browser picker on click, guarding TypeError for pickerless input types and keeping the call inside a user gesture.
Collect every key across a union of shapes with a distributive conditional - plain keyof only exposes the keys every member shares.
Run versioned migrations in order with an idempotency check: a second pass applies nothing, and applied versions are recorded in state.
Map each tag to a Set of ids in an inverted index, so tag lookups, unions across tags, and removals that prune empty buckets all stay cheap.
Feature-detect navigator.share, validate payloads with navigator.canShare before calling it, and await the promise the share sheet resolves.
Index reads become T | undefined under noUncheckedIndexedAccess: guard array and Record lookups explicitly and narrow without assertions.
Numeric index signatures type array-like records by position, while runtime keys stay strings — Object.keys returns string keys even for ids.
Define recursive tree types where children use the node type itself, then fold every subtree with one generic combine function instead of ad hoc loops.
Keep one list item tabbable while arrow keys move focus between options, wrapping at the ends, the standard roving tabindex pattern.
Highlight the section the reader is in with IntersectionObserver and a narrow rootMargin band, then sync aria-current on the matching nav link.
Listen for scrollend instead of debounced scroll events: it fires once scrolling has fully settled, which is the right moment to append a page.
Open the OS file dialog from a click handler with showOpenFilePicker, feature-guard the API surface, and treat AbortError as a dismissed dialog.
A one-line mapped type flattens Defaults & Overrides intersections so hover tooltips and ExpectEqual comparisons show a single clean object shape.
Listen for slotchange on shadow-DOM slots and read assignedElements() so slot membership counters stay in sync with light-DOM nodes as they move.
Listen for the storage event to react to localStorage changes made in other tabs - the writing tab itself never receives the event.
Each class field needs an inline initializer, a constructor assignment, or an optional marker — the strict build rejects anything that could read as undefined.
Template literal index signatures type whole families of dynamic keys — CSS vars must carry the -- prefix and event keys only known on-suffixes.
A truthiness check drops falsy members like empty string and 0 from literal unions, but a plain number still includes zero — equality checks are required there.
Persist typed preferences through localStorage with an unknown-narrowing guard so corrupted JSON or wrong shapes fall back to defaults.
Type column definitions against the row's own keys so unknown keys fail compilation and each format callback gets the fully typed row.
Push a fresh snapshot before every mutation: undo pops to the previous state, redo replays the future, and any new edit clears the redo stack.
Flip a union of option objects into an intersection through contravariant function positions, so merged option sets require every member.
Render only the rows inside the scroll viewport and give a spacer the full height, so a 5000-row list paints a dozen nodes per frame.
Count in-flight tasks with a WaitGroup: add before spawning, done in each task, and await wait() so the program resumes exactly when all work drained.
Roll one random number against cumulative weights so each item wins with probability proportional to its weight, then verify the split over many draws.
Open the print dialog with window.print() and use beforeprint/afterprint listeners to swap chart markup for print-friendly tables and restore it after.
ARIA states expose typed reflection properties such as ariaInvalid and ariaLive, replacing setAttribute strings with compiler-checked assignments.
at() returns T | undefined for out-of-range and negative indexes, replacing optimistic bracket indexing with an honest type you can handle once.
input.list exposes the bound datalist element and datalist.options enumerates suggestions, so free-typed values get a manual membership check.
A diagnostics channel publishes named telemetry that any module can subscribe to, decoupling instrumentation from the code that emits requests.
Two ECDH P-256 key pairs derive identical shared bytes via diffieHellman, which a SHA-256 hash turns into a symmetric session key.
flatMap maps and flattens exactly one array level, so triple-nested arrays stay partially nested and branches must return arrays for a consistent element type.
Type message catalogs with a mapped Renderer so each key accepts exactly its own argument tuple, while satisfies checks every locale without widening keys.
Iterator helpers chain filter, take, and map lazily, but the resulting iterator is single-pass: a drained chain yields nothing on a second consumption.
platform() returns a literal union of platform names, so build-script branches on win32, darwin, and linux are exhaustively checkable.