【发布时间】:2021-03-27 01:20:02
【问题描述】:
我有一个函数可以在给定目录路径的情况下动态导入一堆文件。但是,我正在为如何输入这个问题而摸不着头脑。
export const fileHandler = async (
dirPath: string
) => {
// the list of js/ts files within the directory
const files = readdirSync(dirPath).filter(
(f) => f.endsWith('.js') || f.endsWith('.ts'),
);
for (const file of files) {
const resolvePath = path.join(dirPath, file);
// type ModuleType = Promise<typeof import(resolvePath)>; // String literal expected.
const defaultImport = (await import(resolvePath)).default; // Unsafe member access .default on an any value
// do something with it...
}
}
我知道import(...) 需要一个静态路径来安全输入。但是如何在允许函数接受任何目录路径的同时键入 import。
【问题讨论】:
-
你想要的类型是什么?