【问题标题】:Typing dynamic import键入动态导入
【发布时间】: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。

【问题讨论】:

  • 你想要的类型是什么?

标签: typescript dynamic-import


【解决方案1】:

我想通了。

由于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

【讨论】:

    猜你喜欢
    • 2021-02-03
    • 2019-10-31
    • 2012-06-07
    • 2021-01-05
    • 2018-11-19
    • 2017-12-12
    • 2018-11-11
    • 2019-05-28
    • 2022-11-11
    相关资源
    最近更新 更多