Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the return type of a dynamic import?

I have a file, which must be loaded asynchronously, so I made a function, which loads this file and returns the Promise:

export function load() {
    // ...
    return import(filename);
}

What is the return type of this Function? Promise<any> works, but it feels very weird. I'd like to write the signature as.

export function load() -> Promise<???>;
like image 389
Tim Diekmann Avatar asked Aug 31 '18 09:08

Tim Diekmann


People also ask

What does dynamic import return?

Dynamic import of modules It returns a promise and starts an asynchronous task to load the module. If the module was loaded successfully, then the promise resolves to the module content, otherwise, the promise rejects.

What are dynamic imports?

Dynamic imports or Code Splitting is the practice of breaking up your JavaScript modules into smaller bundles and loading them dynamically at runtime to improve and increase the performance of your website dramatically.

What is dynamic import in React?

Unlike static imports, React's dynamic imports don't bundle the module at compile time. Rather, when the component is about to render for the first time, React will resolve the promise and load the corresponding module, swapping it in as the app is running.

Why do we need to use dynamic imports?

Dynamic module imports play a very important role if you want your code to be fast and more performant. Most of the time, you don't have to load all those heavy and bulky files in one go. It will be super helpful if we can somehow import those files whenever they are required.


Video Answer


1 Answers

You need to use an import type and TypeScript 2.9 or higher. Here is an example:

my_module.ts

export const user = { name: "John", age: 30 };
export const event = { name: "Birthday", date: new Date(1989, 13, 2) };

demo.ts

type ModuleType = typeof import("./my_module"); // This is the import type!

export function load(): Promise<ModuleType> {
    // ...
    return import("./my_module");
}

(async () => {
    const module = await load();
    console.log(module.user.age); // It works!
})();

tsconfig.json (Added for reference)

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "es2015",
      "dom"
    ], 
    "strict": true,  
    "esModuleInterop": true
  }
}
like image 104
Remo H. Jansen Avatar answered Oct 18 '22 10:10

Remo H. Jansen