动态导入的返回类型是什么?

Tim*_*ann 13 typescript typescript2.4

我有一个必须异步加载的文件,所以我创建了一个函数,它加载这个文件并返回Promise

export function load() {
    // ...
    return import(filename);
}
Run Code Online (Sandbox Code Playgroud)

这个函数的返回类型是什么?Promise<any>有效,但感觉很奇怪。我想把签名写成这样。

export function load() -> Promise<???>;
Run Code Online (Sandbox Code Playgroud)

Rem*_*sen 13

您需要使用导入类型和 TypeScript 2.9或更高版本。下面是一个例子:

my_module.ts

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

演示文件

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!
})();
Run Code Online (Sandbox Code Playgroud)

tsconfig.json(添加以供参考)

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "es2015",
      "dom"
    ], 
    "strict": true,  
    "esModuleInterop": true
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这不会在第一行开始加载模块吗?或者 TypeScript 是否足够聪明,知道 typeof import 将被忽略? (6认同)

Ian*_*ell 7

在最新的 React 中,动态导入类型是:

type DynamicImportType = () => Promise<{ default: React.ComponentType<any>; }>;
type LazyComponentType = React.LazyExoticComponent<React.ComponentType<any>>;

const dynamicImport: DynamicImportType = () => import('./MyComponent');
const LazyComponent: LazyComponentType = React.lazy(dynamicImport);
Run Code Online (Sandbox Code Playgroud)

资源

  • 不为我工作。`const importPromise: DynamicImportType = () =&gt; import('./components/MyComponent');` 行给了我这样的错误: 类型 'typeof ... 中缺少属性 'default' 但类型 '{ default 中需要: 组件类型&lt;任意&gt;; }'.ts(2322)。你知道如何解决吗? (4认同)