我有一个文件,其中 必须被异步加载,所以我做了一个函数,它加载这个文件并返回 Promise
:
export function load() {
// ...
return import(filename);
}
这个函数的返回类型是什么?
Promise<any>
有效,但感觉很奇怪。我想把签名写成这样。export function load() -> Promise<???>;
最佳答案
您需要使用导入类型和 TypeScript 2.9或更高。下面是一个例子:
my_module.ts
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!
})();
tsconfig.json(添加以供引用)
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": [
"es2015",
"dom"
],
"strict": true,
"esModuleInterop": true
}
}
关于typescript - 动态导入的返回类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52112948/