Reputation: 189
I have a function that dynamically import a bunch of files given a directory path. However, I'm scratching my head on how I would type this.
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...
}
}
I understand that import(...)
wants a static path for safe typing. But how do I type import while allowing the function to accept any directory path.
Upvotes: 1
Views: 6627
Reputation: 189
I figured it out.
Since dirPath
and resolvePath
are dynamic (only known at runtime), the import(resolvePath)
type is also only available at runtime. That is why TypeScript was complaining about type safety and wants a static path.
If you know the file type of the files you're dynamically importing
const myFile: FileType = {
foo: 'FOO',
bar: 'BAR'
}
export default myFile;
you can type cast it
type ModuleType = {default: FileType};
const defaultImport = (await import(resolvePath) as FileType).default
Upvotes: 3