我有一个文件,必须异步加载,所以我创建了一个函数,它加载这个文件并返回Promise
:
export function load() {
// ...
return import(filename);
}
这个函数的返回类型是什么? Promise<any>
工作,但感觉非常奇怪。我想把签名写成。
export function load() -> Promise<???>;
您需要使用导入类型和TypeScript 2.9或更高版本。这是一个例子:
export const user = { name: "John", age: 30 };
export const event = { name: "Birthday", date: new Date(1989, 13, 2) };
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!
})();
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": [
"es2015",
"dom"
],
"strict": true,
"esModuleInterop": true
}
}
使用最新的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);
React.lazy
LazyExoticComponent
中搜索“the React types”