Dynamic imports and type assertions
What you'll learn: How to type dynamic import() expressions that load modules at runtime conditionally.
The runtime module loading problem
So far, you've worked with static imports—modules loaded at the top of your file before any code runs. But sometimes you need to load code conditionally or lazily, like loading heavy components only when a user clicks a button. That's where dynamic imports come in.
In TypeScript, the dynamic import() function returns a Promise that resolves to the module's exports. The challenge is preserving type safety for something that doesn't exist until runtime.
Basic dynamic import typing
When you call import(), TypeScript infers the module type based on the target file:
async function loadConfig() {
// TypeScript knows what './config' exports
const configModule = await import('./config');
// Full type safety on configModule's exports
configModule.apiUrl;
configModule.timeout;
}
The type of configModule matches exactly what './config' exports.
Type assertions with dynamic imports
Sometimes you need to assert the shape of a dynamically loaded module, especially when the import path is computed at runtime:
type UserModule = {
name: string;
age: number;
};
async function loadUserData(userId: string) {
const path = `./users/${userId}`;
const module = await import(path) as { default: UserModule };
return module.default;
}
The as assertion tells TypeScript what shape to expect from the unknown dynamic path.
Combining with typeof for re-exported types
You can extract types from statically imported modules and apply them to dynamic imports:
import type { Config } from './config';
async function loadConfigDynamic(): Promise<Config> {
const module = await import('./config');
return module as unknown as Config;
}
This pattern is useful when you want the type information without triggering an eager module load.
Key takeaway: Dynamic import() returns a typed Promise based on the module path, and you can use type assertions to handle runtime-computed paths while maintaining type safety where possible.