Const Assertions Build Literal Lookup Tables
Freeze lookup tables with as const so keyof typeof yields exact key unions, arrays expose element unions, and Record mismatches fail at compile time.
Page 3 of 6
Freeze lookup tables with as const so keyof typeof yields exact key unions, arrays expose element unions, and Record mismatches fail at compile time.
elementFromPoint answers which element owns a viewport coordinate, and an overlay intercepts hits until it opts out with pointer-events none.
Declare capability surfaces with interfaces and make classes opt in via implements, so missing members or wrong signatures fail at compile time.
Pull field types along object paths with indexed access types, so renamed config fields keep their derived types in sync without hand-written duplicates.
Model PATCH payloads with Partial<T> so clients may set any subset of keys, merge with spread, and remember nesting still replaces whole objects.
Define arbitrary-depth JSON payloads with a recursive type alias and walk them with narrowing, counting leaves and tracking nesting depth in one pass.
Attach per-field messages with setCustomValidity, clear them with an empty string to restore built-in checks, and arbitrate submission with checkValidity.
Force subclasses to implement storage contracts with abstract members while concrete helpers on the base class keep shared logic in one place.
A generic combinator lifts an element-level predicate into a whole-array guard, so validate-then-use code narrows unknown[] to T[] after a single check.
Interleaving layout reads and writes forces synchronous reflows; batching all getBoundingClientRect calls before style writes keeps one layout per frame.
Compose behaviors onto classes with mixin functions whose Constructor parameter preserves the base constructor signature and stacks instance types.
closest walks the ancestor chain to the first matching selector, and its generic form hands back the concrete element class for dataset access.
ConstructorParameters and InstanceType recover constructor tuples and instance types from class definitions, so factories stay typed without repeated shapes.
customElements.define with observedAttributes turns HTML attributes into a typed config surface, and an HTMLElementTagNameMap entry types createElement calls.
Wire a confirm dialog with typed event listeners: cancel is cancelable, close(reason) sets returnValue, and querySelector narrows type and null in one generic.
Naked type parameters in conditional types evaluate each union member and rebuild the union; tuple-wrapping the parameter disables the split.
element.animate drives keyframes from script — a horizontal shake on failed validation — with a finished promise that resolves when the run ends.
TypeScript 5.5 infers type predicates from filter callbacks whose returned expression narrows the element, so results stay narrowed without hand-written guards.
Generator signatures declare yield values, the return value, and next() arguments as three separate slots; for-of sees only the yields.
Generic type defaults supply sensible second arguments — Error for results, string cursors for pages — while explicit call sites can still override them.
Type one function parameter as Iterable<T> so arrays, Sets, Map views, and generators all flow through the same loop without per-type overloads.
Give one property a narrow read type and a wider write type: the setter accepts string or number while the getter always hands back a number.
Route single-page apps with typed history state: pushState stores a typed payload, and popstate reads it back with a null guard.
Index signatures accept any string key: reading an absent glyph yields undefined at runtime, so presence checks with in guard every lookup.
instanceof checks double as type guards: each branch sees the concrete element class with its own properties instead of the bare Element shape.
Intrinsic string types apply case transforms at the type level, so handler names and env keys derive from existing keys and renames propagate automatically.
Read and patch object properties through keys constrained by keyof, so wrong key names and mismatched value types both fail compilation.
matchMedia evaluates a CSS breakpoint once and pushes updates through change events, keeping JS layout decisions on the same query string as the stylesheet.
NoInfer pins type inference to one argument, so out-of-scope callback values fail compilation instead of silently widening the type parameter.
Object.keys returns string[] and loses the key union; a small keysOf generic restores keyof T so loop variables stay precisely typed.
Mark members that replace base-class implementations with override so accidental shadows and signature drift fail compilation under noImplicitOverride.
Derive wrapper arguments and return values from an existing function with Parameters and ReturnType, so a signature change flows through instead of diverging.
Accept Partial<RetryOptions> from callers and merge over Required defaults, so every field of the resolved options object is guaranteed present.
Return this from chainable methods so subclasses keep their own methods available: limit() can precede orderBy() and the types still line up.
Promise.allSettled never rejects as a whole: each result carries a status discriminant, narrowing to value on fulfilled and unknown reason on rejected.
Signatures that accept ReadonlyMap and readonly arrays expose views without mutation methods, so internal state stays writable while callers stay read-only.
Type a lookup table as Record over a union so a missing or extra plan is a compile error, and derive the key list from the table instead of retyping it.
A recursive mapped type collects every leaf dot path of a nested config, and a readPath helper typed over those paths makes invalid keys a compile-time error.
Type methods with an explicit this parameter so detached calls fail compilation, and bind() restores the context instead of silently losing state.
Keep type-only imports erased from the runtime output with import type, while value imports stay real and usable at execution time.
A listener helper keyed by HTMLElementEventMap narrows the callback event type from the event name and returns an unbind function for exact cleanup.
Annotate type parameters with in and out to turn silent bivariance into compile errors, before a wrong-direction assignment fails only at runtime.
Assign functions that return anything to a void-typed callback contract; the value is simply ignored, while a void function cannot fill a typed slot.
Store document.activeElement when a widget opens and restore focus to it on close, so keyboard users return to the trigger instead of the body.
@ts-expect-error marks a line that must fail to compile, so a fixed bug or a loosened type turns the stale directive itself into a build error.
Read resolved styles and custom properties with getComputedStyle; values arrive as strings, so parse numbers yourself before writing scaled values back.
Read number inputs with valueAsNumber instead of parsing .value by hand; empty or invalid fields yield NaN that Number.isNaN can catch before math.
Interfaces extend object shapes and merge across declarations; type aliases compose unions and intersections, and each side covers jobs the other cannot.
Optional properties let the whole key go missing, while a required prop of type T or undefined must exist; in checks and spreads tell the two apart.
Pass an explicit accumulator type to reduce when the initial value cannot carry it, so never[] widening is caught and Record or Map builders type-check.
Read a select through value, selectedIndex, options, and selectedOptions; programmatic value assignment fires change just like user selection.
Chunk CPU-heavy loops and await a setImmediate between slices so pending callbacks interleave and the process never blocks for the whole run.
structuredClone copies data by structure: the generic result still claims T, but class methods and prototypes are gone unless you reattach them.
Call signal.throwIfAborted() at stage boundaries so a cancelled pipeline stops between steps and surfaces rejection as AbortError, not wasted computation.
Derive timer handle types with ReturnType<typeof setTimeout> so one codebase compiles against both the DOM number and the Node Timeout object.
Unwrap layered promises with the Awaited utility so ReturnType, Promise.all elements, and Promise<Promise<T>> wrappers all resolve to the final value type.
Catch variables are unknown under strict mode: narrow with instanceof before reading message, and handle non-Error throw values with an explicit branch.
Derive a closed union from an as const allowlist array and narrow strings into it with a predicate, so unknown commands are rejected before dispatch.
Const type parameters stop inference from widening literals: config.mode stays "strict" instead of string, so keys and values keep their literal types.
Two interface declarations with the same name merge into one: fields from every declaration become required together and keyof unions reflect the full set.
Union members without a shared discriminant are narrowed with the in operator: checking key presence gives each branch its exact shape and fields.
NonNullable removes null and undefined from a union, turning optional draft fields into present values once a normalization step has filled them.
Object.create(null) builds lookup maps without Object.prototype, so inherited names like constructor cannot shadow user keys or leak through for-in scans.
Promise.all preserves the tuple shape of its input array, so destructured results keep per-element types instead of collapsing into one unioned array.
querySelector with a generic parameter types the result as HTMLInputElement, so files, checked, and value arrive typed instead of as plain Element.
addEventListener("submit") infers SubmitEvent in TypeScript, so submitter and preventDefault arrive typed instead of as a loose Event parameter.
Wrap any function with a timing helper while variadic tuple types forward the original argument and return types, so each wrapped call keeps its own signature.
Merge several AbortControllers into one downstream signal with AbortSignal.any so a cancel from any source reaches every consumer with the original reason.
Guard a boundary with an assertion function whose asserts return type narrows the caller variable after the call, throwing a TypeError on invalid shapes.
Release async resources deterministically with await using and Symbol.asyncDispose, which runs when the block exits even if the body throws.
Narrow unions at the type level with Extract, Exclude, and NonNullable, mirroring each type operation with the matching array filter at runtime.
Load images as they approach the viewport with IntersectionObserver: rootMargin gives lead time, each image is unobserved after load, teardown calls disconnect.
Serialize an allow-list of fields with a JSON.stringify array replacer, indent output, and restore typed values on parse with a reviver.
Document each slot of a fixed-shape return with labeled tuple elements, so destructured parser results read clearly at the call site while staying plain arrays.
Transform every value of an object with Object.entries and rebuild it via Object.fromEntries, keeping keys intact through rounding, renaming, and sorting.
Bucket records with Object.groupBy for string keys and Map.groupBy for arbitrary keys, replacing hand-rolled reduce accumulation without touching the source.
Read nested config with optional chaining and nullish coalescing, where 0 and empty string stay valid because ?? only falls back on null and undefined.
Keep a class invariant with a #private field and a typed getter/setter pair, so every write path, method or direct assignment, passes the same validation.
Create externally settled promises with Promise.withResolvers and share one as a start gate that several async workers await before the main flow releases them.
Compute set algebra with the ES2025 Set methods union, intersection, difference, and symmetricDifference, plus isSubsetOf and isDisjointFrom relation checks.
Extract element, return, and promise types with conditional types and infer so utility types read the shape instead of duplicating it.
Stream records through async generators so each stage pulls at the pace of the consumer and memory stays flat regardless of source size.
Derive DTO and handler types from a domain type with mapped types and as-clause remapping so renames propagate automatically.
Parse route patterns at the type level with template literal types and infer so path parameters are extracted and checked without runtime regex duplication.
Validate untrusted JSON with unknown-typed inputs and hand-written type guards so every field is checked before it reaches business logic.
Implement an adapter to bridge incompatible interfaces with type-safe conversion for legacy integration.
Use AsyncLocalStorage for request-scoped correlation IDs without explicit parameter passing.
Run async tasks in a typed concurrency pool collecting results in order with proper type inference.
Retry async operations with typed error classification and exponential backoff for resilient service calls.
Write items in batches with backpressure detection pausing when downstream is slow for flow control.
Hash and verify passwords with bcrypt using configurable salt rounds for adaptive cost hashing.
Implement a typed bloom filter with configurable hash count and bit size for probabilistic set membership.
Create branded nominal types with runtime validation guards for type-safe data handling across module boundaries.
Implement a typed builder pattern with fluent interface and compile-time required field checking.
Implement a typed circuit breaker state machine with closed open half-open transitions and metrics.
Implement a fixed-capacity circular buffer with O(1) push and read for streaming window statistics.
Use class-validator decorators with validation pipes for DTO validation in NestJS-style controllers.
Load and validate configuration from environment variables with Zod schema and defaults.
Debounce async function calls with cancel tokens and pending state tracking for UI input handling.
Memoize method results via a decorator with configurable cache key generation for expensive computations.