键入动态导入

问题描述

我有一个函数,可以动态导入给定目录路径的一堆文件。但是,我正在摸索如何打字。

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 。

解决方法

我想通了。

由于 dirPathresolvePath 是动态的(仅在运行时已知),因此 import(resolvePath) 类型也仅在运行时可用。这就是 TypeScript 抱怨类型安全并需要静态路径的原因。

如果您知道要动态导入的文件的文件类型

const myFile: FileType = {
  foo: 'FOO',bar: 'BAR'
}
export default myFile;

你可以输入它

type ModuleType = {default: FileType};
const defaultImport = (await import(resolvePath) as FileType).default