0
0
Typescriptprogramming~5 mins

Dynamic imports with types in Typescript

Choose your learning style9 modes available
Introduction

Dynamic imports let you load code only when you need it. Using types helps keep your code safe and clear.

When you want to load a big library only if the user clicks a button.
When you want to split your app into smaller parts to make it faster.
When you want to load different modules based on user choices.
When you want to reduce the initial loading time of your app.
Syntax
Typescript
const module = await import('./path/to/module');
// With types:
const module: typeof import('./path/to/module') = await import('./path/to/module');

You use await import() to load modules dynamically.

Adding typeof import() tells TypeScript what type the module has.

Examples
Loads the math module dynamically and uses its add function.
Typescript
const mathModule = await import('./math');
console.log(mathModule.add(2, 3));
Loads math with type info so TypeScript knows what functions are available.
Typescript
const mathModule: typeof import('./math') = await import('./math');
const result = mathModule.multiply(4, 5);
console.log(result);
Shows how to use dynamic import with types inside an async function.
Typescript
async function loadAndUse() {
  const mod: typeof import('./utils') = await import('./utils');
  mod.doSomething();
}
Sample Program

This program loads a greetings module only when needed. It uses the sayHello function from that module and prints a greeting.

Typescript
async function main() {
  // Dynamically import the greetings module with type info
  const greetings: typeof import('./greetings') = await import('./greetings');
  console.log(greetings.sayHello('Alice'));
}

main();
OutputSuccess
Important Notes

Dynamic imports always return a promise, so use await or .then().

Using typeof import() helps TypeScript check your code and gives better autocomplete.

Make sure the module path is correct and the module exports what you expect.

Summary

Dynamic imports load code only when needed, improving app speed.

Adding types with typeof import() keeps your code safe and clear.

Use await import() inside async functions to get the module.