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

Order the variables in the dropdown menu based on the PHP variables

I currently have a select list that allows me to choose between two options: Popularity and Recently Ordered. My goal is to filter the objects on the page based on these attributes, connecting each option to its respective function in my dataloader.php fi ...

The specified 'Object' type does not match the required 'Document' constraint

I need assistance with running a MERN application to check for any issues, but I keep encountering this error across multiple files. Error: The 'CatalogType' type does not meet the requirements of 'Document'. The 'CatalogType&apo ...

Is the on-error event not functioning properly in the <img> tag?

I am currently utilizing VueJS to develop the front-end of a project and encountered an issue with the image tag when loading images. Template <div class="items" transition="fade" v-for="item in list"> <img :src="item.logoPath" @error="replac ...

Trouble arises with Javascript object destructuring when used with this.props in React

Just recently I discovered object destructuring with a basic object, which worked perfectly. However, when attempting to apply it in React on this.props, all my variables are returning as undefined. I'm unsure of what mistake I might be making here. A ...

Using conditional logic to check if a column cell is empty

I need help writing a Javascript function that will loop through rows in a table and only change the background color of cells in "column2" if they are empty. My current code is not working as expected, as it colors all rows instead of just those with empt ...

Utilize Google Maps geocoding functionality to pinpoint a location and then

I've encountered this strange phenomenon, but first let's take a look at the code: HTML <div ng-app='maptesting'> <div ng-controller="MapCtrl"> <div id="map_canvas" ui-map="myMap" style ...

What is the best way to implement a gradual decrease in padding as the viewport resizes using JavaScript

My goal is to create a responsive design where the padding-left of my box gradually decreases as the website width changes. I want the decrease in padding to stop once it reaches 0. For instance, if the screen size changes by 1px, then the padding-left sh ...

Error: protractor encountered an unexpected issue

Currently, I am following this tutorial I went through all the steps mentioned in the tutorial except for what was suggested in this post instead of npm install -g protractor I opted for npm install -g protractor --no-optional So far, I have succe ...

Strategies to manage or prevent a timezone offset while deploying a Next.js application on Vercel

Is there a way to ensure that a React/Next.js App always displays the local time in CEST, regardless of the user's location? For example, if I receive GMT time from the backend and want to offset it to display the CEST timezone, how can I achieve this ...

"Encountering issues with Angular2's FormBuilder and accessing nested object properties,

As I dip my toes into TypeScript and Angular2, I find myself grappling with a nested object structure in an API. My goal is to align my model closely with the API resource. Here's how I've defined the "Inquiry" model in TypeScript: // inquiry.ts ...

Optimal approach for handling large JSON files

I am in possession of a JSON file containing approximately 500 lines. I am hesitant to simply dump this JSON data into the end of my Node.JS file as it doesn't seem like the most efficient approach. What alternatives or best practices can be recommend ...

The AJAX request encountered an error while trying to send a POST request to the http://localhost/upload/undefined endpoint. The

I've been scouring the internet and testing for hours, but I'm still unable to identify the source of the error. I could really use some assistance here. I meticulously followed a tutorial on multiple file uploads with drag & drop functionali ...

In Node.js, it is essential to use req.session.save() to ensure that sessions are properly saved

While developing a website with Node.js, Express, and Redis for session management, I noticed an issue where my session variable (isLoggedIn) wasn't being saved after refreshing the page. Strangely, calling req.session.save() after setting the variabl ...

Transitioning to TypeScript has brought the promise of imports returning once again

I've been facing some challenges while migrating my extensive project to TypeScript, particularly with handling imports. Being relatively new to programming, I'm unsure if my previous approach was considered bad practice. Previously, I organized ...

Tips on getting the dropdown value to show up on the header when it changes using Angular 2 and TypeScript

I need assistance with creating a dropdown field in Angular2. When the user selects "car", I want it to display beside the heading. Can anyone provide guidance on how to achieve this? HTML: <h1>Heading <span *ngFor= "let apps of apps">({{apps ...

Add or remove an ID from the swatch gallery based on its presence or absence

I'm currently working on a handleClick function for a gradient swatch gallery. The goal is to add an id of "bg-gradient" to the clicked element, and if another swatch is clicked, remove that id from the previously clicked swatch and add it to the newl ...

What does React default to for the implementation of the ``shouldComponentUpdate`` lifecycle method in its components?

Having a personalized approach to the shouldComponentUpdate() method as part of the React component lifecycle is not obligatory. I am aware that it serves as a boolean function determining whether the render() function will be triggered by changes in comp ...

The hyperlink functionality is disabled because Javascript is set to return false

JS Fiddle Example When using the 'FOO' and 'BOO' items in the navigation bar to open dropdown boxes, I have implemented a code that closes them when a click event occurs outside. This code has been working fine as shown below: $(docum ...

Validating image dimensions with the data-parsley plugin

Is there a way to validate image dimensions with data-parsley? I attempted the code below, but it is not working. data-parsley-dimensions-options='{ "min_width": "100", "max_width": "100", "m ...

Automatically navigate to the bottom of the page by applying the overflow auto feature

I've been working on a chat application using Vue.js. I have set the overflow property to auto for my div element. My goal is to automatically scroll to the bottom of the div so that users won't have to manually click the scrollbar to view the la ...