Concept Flow - Dynamic imports with types
Start
Call import()
Load module asynchronously
Module loaded
Use module with typed import
End
Dynamic imports load modules asynchronously and allow using types to keep code safe.
async function loadModule() { const mod = await import('./mathUtils'); const result: number = mod.add(2, 3); console.log(result); }
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Call loadModule() | Starts async function | Function started |
| 2 | Execute import('./mathUtils') | Loads module asynchronously | Promise pending |
| 3 | Await import resolves | Module loaded | mod = { add: function } |
| 4 | Call mod.add(2, 3) | 2 + 3 | 5 |
| 5 | Assign result: number = 5 | Type checked as number | result = 5 |
| 6 | console.log(result) | Prints to console | Output: 5 |
| 7 | Function ends | No more code | End |
| Variable | Start | After Step 3 | After Step 5 | Final |
|---|---|---|---|---|
| mod | undefined | { add: function } | { add: function } | { add: function } |
| result | undefined | undefined | 5 | 5 |
Dynamic imports use import() to load modules asynchronously.
Use await to get the module object.
TypeScript types the imported module for safety.
Example: const mod = await import('./mod');
Then use mod's exports with types.
Errors happen if module path is wrong.