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或更高版本。下面是一个例子:
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)
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": [
"es2015",
"dom"
],
"strict": true,
"esModuleInterop": true
}
}
Run Code Online (Sandbox Code Playgroud)
在最新的 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)
React.lazyLazyExoticComponent”| 归档时间: |
|
| 查看次数: |
11057 次 |
| 最近记录: |