Top-Level Await and Module Types
You'll learn: How top-level await changed JavaScript's module system and the typing challenges it created for TypeScript.
What Top-Level Await Changed
Before ES2022, you could only use await inside async functions. Top-level await allows you to use await directly at the module's top level—no wrapping function needed.
// Before: had to wrap in an async function
(async () => {
const data = await fetch('/api/data');
})();
// After: top-level await (ES2022+)
const data = await fetch('/api/data');
export const result = data.json();
Seems simple, right? But this fundamentally changed how modules work.
The Module Execution Problem
When a module uses top-level await, it becomes asynchronous. This means:
- The module doesn't finish evaluating immediately
- Any module that imports it must wait for that
awaitto resolve - Module execution order becomes async-dependent
Think of it like a chain reaction: if Module A awaits something, and Module B imports Module A, Module B can't finish loading until A's await completes. The entire module graph becomes asynchronous.
TypeScript's Typing Challenge
TypeScript must track which modules are "async" without actually running the code. The type system needs to know:
- Is this module synchronous or asynchronous?
- Can I safely import this in a non-async context?
- What happens to circular dependencies with awaits?
Currently, TypeScript handles top-level await but doesn't expose explicit "async module" types. It relies on your module and target settings—you need module: "esnext" or "system" and modern target to use top-level await at all.
The challenge: TypeScript can't warn you about performance implications of awaiting at module scope, only whether the syntax is valid for your configuration.
Key Takeaway: Top-level await transforms modules from synchronous code blocks into asynchronous evaluation boundaries, creating type system challenges around module timing that TypeScript handles through configuration rather than explicit async module types.