Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Infinite Scroll Implementation in TypeScript

14 min readintermediate
Website QA and SEO audits

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

  • ✓Infinite Scroll runs in O(n) time and O(n) space, in TypeScript as in every other language.
  • ✓Everything comes from lib.dom.d.ts, so the compiler already knows IntersectionObserverCallback, IntersectionObserverInit and IntersectionObserverEntry, plus AbortController and the signal field on RequestInit.
  • ✓The review note is always the same shape here: model the end of the feed in the type, not in a boolean beside it.
  • ✓The TypeScript trap: IntersectionObserverCallback is declared to return void, and TypeScript's assignability rule for void-returning function types accepts a function returning anything at all.
  • ✓Types are erased, so none of the branding, none of the readonly modifiers and none of the discriminated unions cost a single instruction at runtime.

What Infinite Scroll actually is

Infinite scroll replaces the page-number control with a trigger: as the reader nears the end of what has been rendered, the next slice is fetched and appended. Two decisions determine whether this is smooth or wretched, and neither is the spinner. The first is how the next slice is asked for. OFFSET re-walks and discards every row before the window, so page 400 costs four hundred times page 1, and a row inserted while the reader is scrolling shifts every boundary, which surfaces as duplicated rows and silently skipped ones. Keyset pagination, also called cursor pagination, instead sends the sort key of the last row already delivered and asks for rows strictly after it. That turns the read into one index descent costing the same on page 400 as on page 1, and it stays correct while the underlying set changes beneath it. The second is how arrival is detected. Sampling scroll offsets runs work on every scroll event, on the thread that also has to paint. The better shape is a sentinel element watched asynchronously, so the platform reports the crossing rather than the page interrogating it. Then the part everyone forgets: the rendered list only grows, and every appended node is memory the reader will never scroll back to. The eight languages split three ways. Two are the browser and own the sentinel, the scroll box and the growing node list directly. One is a native client whose list is lazy by construction, which turns the trigger into a view-lifecycle question. The other five sit on the server end of the same contract, where infinite means a result set walked in bounded windows rather than materialised, and they disagree sharply about who owns the database cursor and when it is released. One of the five has no standard library answer at all and expresses the window as a borrow the compiler refuses to let escape.

Infinite Scroll in TypeScript: what you actually reach for

Everything comes from lib.dom.d.ts, so the compiler already knows IntersectionObserverCallback, IntersectionObserverInit and IntersectionObserverEntry, plus AbortController and the signal field on RequestInit. What the DOM lib cannot give you is the cursor type: it is a string on the wire, so you brand it with a unique symbol intersection to stop it being interchangeable with every other string in the program. Enable noUncheckedIndexedAccess and entries[0] becomes IntersectionObserverEntry | undefined, which is why entries.some reads better than indexing. Runtime validation of the page payload needs a separate package such as zod.

TypeScript implementation

The review note is always the same shape here: model the end of the feed in the type, not in a boolean beside it. next: Cursor | null forces the caller to handle exhaustion, where hasMore: boolean lets them forget. Page arrays are readonly Tremor[] so an accidental push into rendered state fails the build. The observer callback is annotated as IntersectionObserverCallback rather than inferred, so the entries parameter is typed without a manual annotation. And any as Page on a fetch result is expected to sit next to a parser, not replace one.
typescript
declare const tag: unique symbol;
/** Opaque server token. A plain string will not substitute for it. */
export type Cursor = string & { readonly [tag]: "tremor" };

export interface Tremor { readonly id: number; readonly magnitude: number }
export interface Page { readonly items: readonly Tremor[]; readonly next: Cursor | null }

export class FeedLoader {
  private cursor: Cursor | null = null;
  private inFlight: AbortController | null = null;
  private readonly io: IntersectionObserver;

  constructor(
    private readonly sentinel: Element,
    private readonly append: (items: readonly Tremor[]) => void,
  ) {
    this.io = new IntersectionObserver(this.onIntersect, { rootMargin: "600px 0px" });
    this.io.observe(sentinel);
  }

  // Typed as IntersectionObserverCallback on purpose. Written as an async arrow
  // it would still compile (void return types accept Promise<void>) and every
  // rejection would float, because the DOM never awaits this.
  private readonly onIntersect: IntersectionObserverCallback = (entries) => {
    if (entries.some((e) => e.isIntersecting)) void this.load();
  };

  private async load(): Promise<void> {
    if (this.inFlight !== null) return;
    const ctrl = new AbortController();
    this.inFlight = ctrl;
    try {
      const qs = this.cursor === null ? "" : `?after=${encodeURIComponent(this.cursor)}`;
      const res = await fetch(`/api/tremors${qs}`, { signal: ctrl.signal });
      const page = (await res.json()) as Page; // erased: nothing checked this
      this.append(page.items);
      this.cursor = page.next;
      if (page.next === null) this.io.unobserve(this.sentinel);
    } finally {
      this.inFlight = null;
    }
  }
}

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 Free

The TypeScript-specific trap

IntersectionObserverCallback is declared to return void, and TypeScript's assignability rule for void-returning function types accepts a function returning anything at all. So new IntersectionObserver(async (entries) => { ... }) type-checks cleanly under --strict, verified against tsc 5.5, and every rejection inside that callback becomes an unhandled promise rejection with no call site able to catch it, because the DOM never awaits your function. The branding has a mirrored weakness: Cursor exists only in the checker, so a value cast out of res.json() with as Page was never validated, and a malformed token arrives at the server as an ordinary string.

Performance in TypeScript, beyond the O(n)

Types are erased, so none of the branding, none of the readonly modifiers and none of the discriminated unions cost a single instruction at runtime. That makes the performance question entirely about what you added to compensate for the erasure. A runtime validator over every page is real main-thread work proportional to rows times fields, running at exactly the moment the reader is scrolling. Validate the fields you branch on, the cursor and the ids, and let the display fields through unchecked; the compiler's guarantees end at the network boundary and paying to rebuild them costs frames. The asymptotic cost is the same in every language, O(n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Infinite Scroll between languages.

Real-World Applications

Infinite Scroll is used extensively in production software: web frameworks, content management systems, API gateways, and SPA architectures implement this pattern for handling HTTP requests and rendering. In TypeScript specifically, frameworks like React, Express, and Next.js implement related concepts. Understanding Infinite Scroll helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Infinite Scroll appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Infinite Scroll over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Infinite Scroll to build pattern recognition. In TypeScript, demonstrate proficiency with generics and type guards to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic TypeScript code that is both correct and maintainable.

Frequently Asked Questions

Which TypeScript type or library should I use for Infinite Scroll?

Everything comes from lib.dom.d.ts, so the compiler already knows IntersectionObserverCallback, IntersectionObserverInit and IntersectionObserverEntry, plus AbortController and the signal field on RequestInit. What the DOM lib cannot give you is the cursor type: it is a string on the wire, so you brand it with a unique symbol intersection to stop it being interchangeable with every other string in the program. Enable noUncheckedIndexedAccess and entries[0] becomes IntersectionObserverEntry | undefined, which is why entries.some reads better than indexing. Runtime validation of the page payload needs a separate package such as zod.

What is the most common TypeScript mistake when implementing Infinite Scroll?

IntersectionObserverCallback is declared to return void, and TypeScript's assignability rule for void-returning function types accepts a function returning anything at all. So new IntersectionObserver(async (entries) => { ... }) type-checks cleanly under --strict, verified against tsc 5.5, and every rejection inside that callback becomes an unhandled promise rejection with no call site able to catch it, because the DOM never awaits your function. The branding has a mirrored weakness: Cursor exists only in the checker, so a value cast out of res.json() with as Page was never validated, and a malformed token arrives at the server as an ordinary string.

How does Infinite Scroll actually perform in TypeScript?

Types are erased, so none of the branding, none of the readonly modifiers and none of the discriminated unions cost a single instruction at runtime. That makes the performance question entirely about what you added to compensate for the erasure. A runtime validator over every page is real main-thread work proportional to rows times fields, running at exactly the moment the reader is scrolling. Validate the fields you branch on, the cursor and the ids, and let the display fields through unchecked; the compiler's guarantees end at the network boundary and paying to rebuild them costs frames. Time complexity is O(n) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? Student discounts on developer tools are collected on Noizz, tool by tool.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Want 50 audits a day? Explore SeekerPro

Engagement

0

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.