How to use dynamic imports with typescript?

Viewed 148

Im doing typescript and I want to do dynamic imports based on commands. I have this setup which has no issues

static async GetCommand(command:string):Promise<(this: Discord.Message, ...args: string[]) => Promise<void>> {
    const f = (await import(`./classes/roles/everyone/commands/give_money/command`));
    return f.default;
}

but that is hardcoded to a fixed import location. I want to make it dynamic like this

static async GetCommand(command:string):Promise<(this: Discord.Message, ...args: string[]) => Promise<void>> {
    const f = (await import(`./classes/roles/everyone/commands/${command}/command`));
    return f.default;
}

but then it complains that f is of type any and doesn't compile as a result. How can I fix this?

Thanks

1 Answers

then it complains that f is of type any and doesn't compile as a result.

If you have a dynamic string as an argument to import TypeScript assumed any.

How can I fix this?

Add an explicit annotation if you want the error to go away:

static async GetCommand(command:string):Promise<(this: Discord.Message, ...args: string[]) => Promise<void>> {
    const f: any = (await import(`./classes/roles/everyone/commands/${command}/command`));
    return f.default;
}
Related