Devendra Verma
Devendra Verma

Reputation: 1015

dynamically import type in typesript

I have a file say MyFactory.ts. Content of the file is given below:

export type CommandFactory = () => string[] | undefined;
export enum FactoryIds {commandFactory : 'commandFactory'}

Now I want to dynamically import this file in another file (say main.ts) and use type CommandFactory in it. Content of main.ts is given below:

const Factory = await import('./MyFactory');
const commandFactories : Factory.CommandFactory[] = []; //Here I am getting error that Property 'CommandFactory' does not exist on type 'typeof import('MyFactory')'

While I can easily get FactoryIds by Factory.FactoryIds but not able to access CommandFactory using Factory.CommandFactory. I wanted to know how can I dynamically import CommandFactory type in my main.ts file.

Upvotes: 0

Views: 3890

Answers (1)

Nikita Ivanov
Nikita Ivanov

Reputation: 856

There's no sense in dynamic importing a type since types are static – they are eliminated after compilation. If you need to import types from a module you want to import dynamically, you can import the types separatelly:

import type { CommandFactory } from './MyFactory';

const Factory = await import('./MyFactory');

import type statements are eliminated during compilation, so your module will still be imported only dynamically in runtime.

Upvotes: 8

Related Questions