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

问题描述 投票:-1回答:1

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

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

这个函数的返回类型是什么? Promise<any>工作,但感觉非常奇怪。我想把签名写成。

export function load() -> Promise<???>;
typescript typescript2.4
1个回答
3
投票

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

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

0
投票

使用最新的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);

资源

© www.soinside.com 2019 - 2024. All rights reserved.