输入动态导入
Typing dynamic import
我有一个函数可以在给定目录路径的情况下动态导入一堆文件。但是,我正在摸索如何输入这个。
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。
我想通了。
由于 dirPath
和 resolvePath
是动态的(仅在运行时已知),因此 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
我有一个函数可以在给定目录路径的情况下动态导入一堆文件。但是,我正在摸索如何输入这个。
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。
我想通了。
由于 dirPath
和 resolvePath
是动态的(仅在运行时已知),因此 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