Import an object of classes types from one file to another in typescript

Tags: ,



I have the following object in the file exampleA.ts:

import { ExampleClass } from 'example.ts';
export const dynamicImportations = { ExampleClass };

Then, in the file exampleB.ts I import an array containing class types and use it like this:

import { dynamicImportations } from 'exampleA.ts';
const exampleClass = new dynamicImportations.ExampleClass();

Changing how the dynamicImportations object is import (import { dynamicImportations } from 'exampleA.ts';) can i change this line of code const exampleClass = new dynamicImportations.ExampleClass(); to this const exampleClass = new ExampleClass();?

Answer

Although import (particularly named imports) is sort of superficially similar to destructuring assignment, it isn’t destructuring assignment. It doesn’t have all of the features destructuring assignment has, does at least one thing that destructuring assignment does but differently (renaming), and has features (like the default import, and importing a module namespace object) that destructuring assignemnt doesn’t have. It’s just different. 🙂 So you can’t import dynamicImportations.ExampleClass directly via an import statement. You have to import dynamicImportations, then take the property from it.

So you can either

  1. Keep what you have

    or

  2. Use after-the-fact destructuring:

    import { dynamicImportations } from 'exampleA.ts';
    const { ExampleClass } = dynamicImportations;
    const exampleClass = new ExampleClass();
    
  3. Import the module namespace object, then destructure it; but that’s no better than #2.


I’m not recommending this, but #3 is possible with a single overall statement when you use dynamic import to do it if top-level await (a Stage 3 proposal) is available in your environment:

const {dynamicImportations: { ExampleClass }} = await import("exampleA.ts");
const exampleClass = new ExampleClass();

But it’s important to understand that that’s just this, but in dynamic form:

const * as temp from "exampleA.ts";
const {dynamicImportations: { ExampleClass }} = temp;
const exampleClass = new ExampleClass();

It’s also important to understand that dynamic import may make it harder (or impossible) for bundlers (or the JavaScript engine itself) to tree-shake your code.



Source: stackoverflow