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

Lazy Loading Implementation in TypeScript

11 min readbeginner
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

  • ✓Lazy Loading runs in O(1) time and O(1) space, in TypeScript as in every other language.
  • ✓The compiler contributes no runtime machinery, so the mechanism is whatever the host provides.
  • ✓The empty state wants a unique sentinel, usually a module-private Symbol, and not undefined.
  • ✓The TypeScript trap: Compile const m = await import('./tzdata') with --module commonjs and the emitted JavaScript is await Promise.resolve().then(() => require('./tzdata')).
  • ✓Types cost nothing at runtime, so the number that matters is what the emit does to your holder.

What Lazy Loading actually is

Lazy loading defers the cost of building something until the first caller actually needs it: a parsed rule table, a compiled pattern, a database handle, or a megabyte of code that most sessions never execute. The mechanics look trivial. Check whether a slot is empty, fill it, hand it back. That apparent simplicity is exactly why it stays a durable source of subtle bugs. Two threads can arrive at the empty slot together. A memory model can let one of them publish the reference before the object's own field writes become visible to the other, which is what turns naive double-checked locking into a correctness defect rather than a style preference. A factory that throws leaves a third state, neither empty nor filled, and every runtime answers it differently: retry on the next call, cache the failure permanently, or quietly mark the work done and hand out a zero value. Deferring also moves work rather than deleting it, so one unlucky request pays a latency spike the next thousand do not. The eight implementations here disagree at nearly every level. Four hand you a dedicated once-token in the standard library, and hand-rolling your own there is a review failure. Two make global laziness a language guarantee you cannot switch off, so the whole singleton pattern collapses into one keyword. One erases its lazy declarations entirely at compile time, leaving the emitted behaviour hostage to a compiler flag most teams set once and never read again. One treats a failed initialisation as permanent corruption of the type itself. Two stack a second, unrelated flavour of laziness on top: deferring delivery of the code across a network boundary, with its own syntax and its own failure modes. The big-O is identical everywhere. Almost nothing else is.

Lazy Loading in TypeScript: what you actually reach for

The compiler contributes no runtime machinery, so the mechanism is whatever the host provides. What it does add is a way to name a module purely at the type level: typeof import('./tzdata') describes the module's shape without emitting anything, and Awaited<T> unwraps the promise a real import() returns. import type marks a binding erasable. Between them --module, --target, --moduleResolution and --verbatimModuleSyntax decide whether your deferred import survives compilation at all. Private # fields give a lazy holder encapsulation the checker actually enforces.

TypeScript implementation

The empty state wants a unique sentinel, usually a module-private Symbol, and not undefined. Lazy<number | undefined> is a legal instantiation, and a check against undefined then cannot separate an uninitialised slot from a legitimately undefined value; the checker will narrow confidently in the wrong direction. The second standing habit is annotating every type-only import with import type, so that enabling verbatimModuleSyntax later does not start emitting the import and pull a module you only mentioned in a signature into the runtime graph.
typescript
// A Lazy<T> whose emptiness is modelled in the TYPE, not by a null check.
// undefined is a legal T (Lazy<number | undefined>), so a sentinel object
// is the only discriminator the checker will trust.
const EMPTY = Symbol("empty");

export class Lazy<T> {
  #value: T | typeof EMPTY = EMPTY;
  #factory: (() => T) | undefined;

  constructor(factory: () => T) {
    this.#factory = factory;
  }

  get value(): T {
    if (this.#value === EMPTY) {
      const f = this.#factory;
      if (f === undefined) throw new Error("re-entrant Lazy.value");
      this.#factory = undefined; // trip the wire before calling out
      this.#value = f();
    }
    return this.#value as T;
  }
}

// Type-only reference to a module that is never imported at runtime:
// The typeof import(...) form is erased, so the annotation pulls in no chunk.
type TzModule = typeof import("./tz");

let tz: Promise<TzModule> | undefined;
export function timezones(): Promise<TzModule> {
  // Under "module": "commonjs" tsc rewrites this to
  // Promise.resolve().then(() => require("./tz")) and the split vanishes.
  tz ??= import("./tz");
  return tz;
}

export const sieve = new Lazy<Uint8Array>(() => {
  const s = new Uint8Array(1 << 16).fill(1);
  for (let p = 2; p * p < s.length; p++) {
    if (s[p] === 1) for (let q = p * p; q < s.length; q += p) s[q] = 0;
  }
  return s;
});

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

Compile const m = await import('./tzdata') with --module commonjs and the emitted JavaScript is await Promise.resolve().then(() => require('./tzdata')). That is not a deferred fetch. require is synchronous, the module body runs on the main thread inside a microtask, and a bundler resolving that static require links the module straight into the parent bundle, so the split you configured does not exist. Nothing in the type system reports it, the source is unchanged, and the only symptom is a bundle size that never drops. Setting --module to esnext or preserve leaves the import() call verbatim.

Performance in TypeScript, beyond the O(1)

Types cost nothing at runtime, so the number that matters is what the emit does to your holder. Below --target es2022 a #value field is downlevelled to a module-level WeakMap plus a __classPrivateFieldGet helper, and every read of the lazy slot becomes a has check followed by a get: two hash lookups where the source implied a field load. At es2022 and above the identical source emits a native private field. A lazy wrapper, read on every access to the value it guards, is one of the few places where that gap lands on a hot path. The asymptotic cost is the same in every language, O(1) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Lazy Loading between languages.

Real-World Applications

Lazy Loading 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 Lazy Loading helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Lazy Loading appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Lazy Loading 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 Lazy Loading 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 Lazy Loading?

The compiler contributes no runtime machinery, so the mechanism is whatever the host provides. What it does add is a way to name a module purely at the type level: typeof import('./tzdata') describes the module's shape without emitting anything, and Awaited<T> unwraps the promise a real import() returns. import type marks a binding erasable. Between them --module, --target, --moduleResolution and --verbatimModuleSyntax decide whether your deferred import survives compilation at all. Private # fields give a lazy holder encapsulation the checker actually enforces.

What is the most common TypeScript mistake when implementing Lazy Loading?

Compile const m = await import('./tzdata') with --module commonjs and the emitted JavaScript is await Promise.resolve().then(() => require('./tzdata')). That is not a deferred fetch. require is synchronous, the module body runs on the main thread inside a microtask, and a bundler resolving that static require links the module straight into the parent bundle, so the split you configured does not exist. Nothing in the type system reports it, the source is unchanged, and the only symptom is a bundle size that never drops. Setting --module to esnext or preserve leaves the import() call verbatim.

How does Lazy Loading actually perform in TypeScript?

Types cost nothing at runtime, so the number that matters is what the emit does to your holder. Below --target es2022 a #value field is downlevelled to a module-level WeakMap plus a __classPrivateFieldGet helper, and every read of the lazy slot becomes a has check followed by a get: two hash lookups where the source implied a field load. At es2022 and above the identical source emits a native private field. A lazy wrapper, read on every access to the value it guards, is one of the few places where that gap lands on a hot path. Time complexity is O(1) and space is O(1).

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

Most AI and dev tools have a student plan. See which ones and how to claim them on Noizz.

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.