Infinite Scroll Implementation in TypeScript
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 in TypeScript: what you actually reach for
TypeScript implementation
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 FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(n)
Real-World Applications
Interview Tips & Practice
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).
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 trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
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.