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

时间:2018-08-31 09:57:19

标签: typescript typescript2.4

我有一个文件,该文件 必须异步加载,因此我创建了一个函数,该函数加载该文件并返回Promise

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

此函数的返回类型是什么? Promise<any>有效,但感觉很奇怪。我想将签名写为。

export function load() -> Promise<???>;

3 个答案:

答案 0 :(得分: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(添加以供参考)

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "es2015",
      "dom"
    ], 
    "strict": true,  
    "esModuleInterop": true
  }
}

答案 1 :(得分:1)

queryInput: {text: {text: "antwort", languageCode: "en-US"}} text: {text: "antwort", languageCode: "en-US"} languageCode: "en-US" text: "antwort" queryParams: {contexts: [{,…},…]} contexts: [{,…},…] 0: {,…} lifespanCount: 1 name: "projects/myteachingbot-arxmxd/agent/sessions/myteachingbot-session/contexts/Chatbotcontext524" 1: {name: "projects/myteachingbot-arxmxd/agent/sessions/myteachingbot- session/contexts/Chatbotcontext2",…} lifespanCount: 1 name: "projects/myteachingbot-arxmxd/agent/sessions/myteachingbot-session/contexts/Chatbotcontext2"

counter.ts

export class Counter {} export const list = ['test'];

index.ts

答案 2 :(得分: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);

资源