Bring in a collection of classes of various types from one TypeScript file to another

In my code file exampleA.ts, I define an object as follows:

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

Later, in another file named exampleB.ts, I import an array that includes class types and instantiate it like this:

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

If I change the way the dynamicImportations object is imported (from

import { dynamicImportations } from 'exampleA.ts';
), can I modify this line of code
const exampleClass = new dynamicImportations.ExampleClass();
to look like this
const exampleClass = new ExampleClass();
?

Answer №1

Even though using import may seem similar to destructuring assignment on the surface, it is actually quite different. Importing does not encompass all the functionalities of destructuring assignment. It has its own unique features such as renaming, default imports, and importing a module namespace object. Therefore, you cannot directly import dynamicImportations.ExampleClass through an import statement. Instead, you must import dynamicImportations and then extract the property from it.

You have a few options:

  1. Continue with your current approach

    or

  2. Utilize post-import destructuring:

    import { dynamicImportations } from 'exampleA.ts';
    const { ExampleClass } = dynamicImportations;
    const exampleClass = new ExampleClass();
    
  3. Import the module namespace object and destructure it afterwards; however, this method is not significantly different from #2.


While I do not necessarily suggest this, option #3 can be achieved in a single statement if dynamic import is supported in your environment along with top-level await (a Stage 3 proposal):

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

It's worth noting that this dynamic approach is essentially equivalent to:

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

Additionally, keep in mind that dynamic import could potentially hinder tree-shaking your code for bundlers or the JavaScript engine itself.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to place two stacked buttons side by side in an inline format?

I am trying to rearrange the layout of a bootstrap modal that includes two multiple select elements and two buttons. My goal is to have all controls inline, with the buttons stacked on top of each other. Here's an example of what I'm aiming for: ...

A mistake occurred during the afterAll function, resulting in a TypeError: Unable to access properties of an undefined entity (specifically, trying to read '

While creating my spec file and settings, I encountered an error in the console: 'An error was thrown in afterAll TypeError: Cannot read properties of undefined (reading 'toLowerCase')', What could be causing this error to appear? H ...

Interactive bar chart that updates in real-time using a combination of javascript, html, and

Current Situation: I am currently in the process of iterating through a machine learning model and dynamically updating my "divs" as text labels. My goal is to transform these values into individual bars that visually represent the values instead of just d ...

Error in React Toaster preventing redirect with useHistory() before reaching another page

When I try to display a message using react toaster and then redirect to another page using history.push('/'), the toaster fails to work properly. Instead, the page immediately redirects to the homepage without displaying the toast message first. ...

Incorporate dynamic animations into text wrapping using React

Currently, I am in the process of learning React and have successfully created a flexbox with 6 child containers using the wrap property. Now, I am looking to add animation when the containers wrap onto a new line. I attempted to add a transition animatio ...

The client side script "/socket.io/socket.io.js" was not located, therefore the Express-generator project was used instead

I have been working on integrating the "chat-example" from Socket.IO's official website into an Express-generator generated project while keeping the structure of the project intact. I have made minimal changes to the code to fit it into the existing ...

Material-UI: Tips for aligning pagination button in the center

My attempt to implement Pagination using Material-UI went well, but now I am struggling to center the arrow buttons and page numbers. I initially tried centering them by wrapping them in a <div style={{textAlign: "center"}}>, however this ...

Utilize dynamic components to load varying data sets multiple times

Is there a way to dynamically load a component multiple times and pass data based on certain values so that it will display with real-time information? I came across an example at the following link: In this example, there is a messageComponent with a "m ...

AngularJS efficiently preloading json file

I am just starting to learn about angularJS. Apologies if my question is not very clear. Here is the problem I am facing: I have a JSON file that is around 20KB in size. When I attempt to load this file using the 'factory' method, I am receivin ...

What is the process for defining a global variable within a module in Typescript?

I've already included a global value in my global JavaScript context: const fs = require('fs') For a specific reason, I need to include it in the global scope. Now, I want to create a .d.ts file to declare the global variable with a stron ...

A dynamic modal window built with ReactJS

I am struggling to understand how to make my app function properly. There is a component called ContactAdd that should render the component ModalWindow when clicked. The ModalWindow component requires a parameter called isOpened={this.state.open}. How c ...

Ensure modifications to a variable are restricted within an if statement

I am struggling to find a way to globally change a variable within an if statement and ensure that the modifications persist. User input: !modify Bye var X = "Hello" if (msg.content.includes ('!modify')) { X = msg.content.replace('!modi ...

What is the best way to display a jQuery UI dialog when the page is reloaded?

I am trying to display a jQuery UI dialog when the user tries to reload or close the browser. Here is my code snippet: $(window).bind('beforeunload', function () { $("#confirm").dialog({ width: 500, modal: true, buttons: { ...

Is there a way to retrieve the initial item of a JSON array from an HTML document using Angular 2?

Within the src/assets/ directory, I have a json file called product.json with the following structure: [ { "images": "http://openclipart.org/image/300px/svg_to_png/26215/Anonymous_Leaf_Rake.png", "textBox": "empty", "comments": "empty" }, { "i ...

Plane is constantly cloaked in darkness

I'm having trouble adding a texture to my plane that repeats both horizontally and vertically. Every time I try to apply the texture, it shows up as black. I've attempted to add some lights to the scene, but the issue persists without any errors. ...

Displaying React components for a brief duration of time

I have an existing React component where I need to display another component for a specific duration. Upon mounting or data loading of the parent component, the child component should become visible after 1-2 seconds and then disappear after a few more sec ...

There seems to be a syntax error in the AngularJS/Bootstrap code, with an unrecognized expression

Hey there, I'm currently working on developing an application using Angular and Bootstrap. I've successfully implemented ui.router for routing purposes, but I've encountered an issue when loading the Bootstrap library. The console is showing ...

Transform JSX into JSON or a string, then reverse the process

I am looking to store the state of a React Component in a database. Json.stringify(myComponent); However, when I attempt to reuse the component using JSON.parse, I encounter Error: Objects are not valid as a React child (found: object with keys {type, k ...

"Encountered an issue with combining multiple meshes that share the same geometry but have

I wrote a loop that generates multiple Mesh objects with various geometries, where each mesh corresponds to a specific texture: var geoCube = new THREE.CubeGeometry(voxelSize, voxelSize, voxelSize); var geometry = new THREE.Geometry(); for( var i = 0; i ...

Manipulate JSON data in a Node.js loop

Currently, I am working on a monitoring system that will indicate on a website whether a server is up or down. I have experimented with various methods such as regex and replacement to modify the JSON file. My main objective is to dynamically change the "s ...