typescripttypescript2.4

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<???>;

Solution

  • 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
      }
    }