What is the process of instantiating a class based on its name or type?

My classes are structured as follows:

class FilterWeekScheduleClass {

}

class FilterClassJournal { 

}

const registryFilterClasses = {
  FilterWeekScheduleClass,
  FilterClassJournal
};

class SingletonClassRegister {
  public registeredClasses = {};

  public constructor() {
    for (let obj in registryFilterClasses) {
      // CREATE INSTANCE OF obj LIKE new obj();
    }
  }
}

let a = new SingletonClassRegister();

When creating instances in the constructor of the SingletonClassRegister class based on registryFilterClasses, how should I properly create instances?

I attempted the following approach:

class SingletonClassRegister {
  public registeredClasses = {};

  public constructor() {
    for (let obj of registryFilterClasses) {
      registryFilterClasses[obj.constructor.name] = new obj();
    }
  }
}

Is this the correct way to do it?

Answer №1

To start, it appears that an array is needed for registryFilterClasses:

const registryFilterClasses = [
  FilterWeekScheduleClass,
  FilterClassJournal
];

Next, simply initialize the instances:

for (let cls of registryFilterClasses) {
  let myInstance = new cls();
}

Alternatively, you can use an object as a data source:

const registryFilterClasses = {
  FilterWeekScheduleClass,
  FilterClassJournal
};
// refer to https://eslint.org/docs/rules/object-shorthand
// equivalent to
//    const registryFilterClasses = {
//      FilterWeekScheduleClass: FilterWeekScheduleClass,
//      FilterClassJournal: FilterClassJournal
//    };

for (let key in registryFilterClasses) {
  // key now holds the class name as a string
  let myInstance = new registryFilterClasses[key]();
}

Update: Obtain class name:

class Test {}
Test.name => "Test"

const t = Test;
t.name => "Test"

const i = new t();
i.constructor.name => "Test"

A potential implementation for your registry:

class SingletonClassRegister {
  public registeredClasses = {
    MyClass
  };

  private instances = {};

  getInstanceByClassName(name) {
    if(this.instances[name] == undefined)
      this.instances[name] = new this.registeredClasses[name]();
    return this.instances[name];
  }

  getInstancesForAllRegisteredClasses() {
    return Object.keys(this.registeredClasses)
       .map(name => this.getInstanceByClassName(name));
  }
}

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

Issue regarding angularjs type definitions

I am facing an issue with installing typings for Angular and I need some guidance on how to resolve the error. Any suggestions or assistance would be greatly appreciated! Below is the error message that I encountered: ERROR in C:\Users\test&b ...

Checkbox Event Restricts Access to a Single Class Variable

As a beginner in AngularJS (just diving in this week), I've encountered an issue with a checkbox input connected to an ng-change event. <input type="checkbox" ng-model="vm.hasCondoKey" ng-change="vm.onKeyCheckboxChange()" /> The ng-change even ...

Transforming a sizeable Typescript undertaking into ES6 modules

I am faced with the challenge of transitioning a fairly large app (~650 files) that currently has a mix of ES6 modules and legacy global namespace internal modules and classes. My goal is to convert everything to 100% ES6 modules. Considering an Iterativ ...

Issue with Material UI v5: Uncaught TypeError - Unable to access properties of an undefined object (specifically 'create')

After setting up the ThemeSetting.tsx context, I encountered an issue where I could not utilize <Button><Button> and other components that rely on the theme from Material UI React.js in TypeScript: error TypeError: Cannot read properties of u ...

Navigating the node and npm ecosystems for importing paths

I am currently working with an NPM module that utilizes another local NPM module which contains shared code. Both of these modules are not public, they are only used locally. In my package.json file, I include the shared module like this: "my-shared": " ...

Invoke a general function with corresponding generic parameters

I am currently working on a function that takes another function and its arguments as parameters, then runs the function with the provided arguments and returns the result while maintaining the data types. If the function being provided has a fixed return ...

Tips for using jest.mock with simple-git/promise

I have been attempting to simulate the checkout function of simple-git/promise in my testing but without success. Here is my current approach: jest.mock('simple-git/promise', () => { return { checkout: async () => { ...

Prohibit the use of screen printing in a modern web application developed with Angular or ReactJS

Is there a way to prevent screen capturing and recording, specifically in regards to progressive web apps? While some mobile applications offer this feature, I am curious about the feasibility of implementing it in progressive web apps without requiring an ...

An instructional guide on seamlessly incorporating a TypeScript variable into an HTML element submission method

A problem arises in my Angular 8/Django 3 app as I attempt to incorporate a server-side variable called client_secret into the stripe.confirmCardPayment() method. The error message that keeps popping up is Property 'client_secret' does not exist ...

Error: Unable to locate script.exe when spawning the Nodejs process

When trying to run an exe in my electron app, I am encountering an error. Even though the path is correct, it still throws an error. Uncaught Error: spawn exe/0c8c86d42f4a8d77842972cdde6eb634.exe ENOENT at Process.ChildProcess._handle.onexit (inter ...

Although there may be some issues with tslint, the functionality is operating smoothly

I am in the process of learning tslint and typescript. Currently, I am facing an issue that I need help with. Could you provide guidance on how to resolve it? Despite conducting some research, I have been unable to find a solution. The relevant code snippe ...

Developing an attribute in a constructor using Typescript

My javascript code is functioning perfectly: class myController { constructor () { this.language = 'english' } } However, I encountered an issue when trying to replicate the same in Typescript export default class myController { co ...

Nested Angular formArrays within formArrays

Currently working on inline editing in my project, I am attempting to patch value data from the server. Within my formArray for the accountNumbers array, I am encountering an issue when trying to change the value of inputs. The error message reads: Error: ...

An error occurs when trying to use AWS.Comprehend as a constructor in the aws JavaScript SDK

I'm attempting to utilize the Amazon Comprehend API using the AWS JavaScript SDK. However, I keep encountering Uncaught (in promise): TypeError: undefined is not a constructor (evaluating 'new AWS.Comprehend... ' What am I doing incorr ...

What is the reason behind Typescript flagging a potential undefined value when checking for array length using a greater than comparison but not with an

Consider the following excerpt from a React component: const AccountInformation = (props: { readonly accountData: AccountData | undefined | null }) => { const hasMultipleAccounts: boolean = props.accountData?.customerAccounts?.length === 1 ? false : t ...

Issue with assigning objects to an array

I'm currently working on a TypeScript application and I've run into an issue with assigning values. Here are the interfaces for reference: export interface SearchTexts { SearchText: SearchText[]; } export interface SearchText { Value: st ...

Displaying an error message following the dynamic retrieval of the input field's value

How can I display an error message when a specific field with a value of 0 is not filled out in my Angular reactive forms? In my form, I have added a dropdown which is mandatory and I have implemented validators to ensure it is required. The validator work ...

The error message "Theme does not include property 'navHeight'" is indicating that the 'navHeight' property is not defined within the 'Theme' type. This issue occurs when using MUI v5 syntax with Types

When attempting to incorporate MUI with new props declared in the Interface inside the theme.ts file (as suggested by the MUI docs), I encountered the error mentioned above while theme.palette.primary.main does work. Despite trying various solutions like i ...

Implementing TypeScript module resolution with Cucumber-js can be a bit tricky

Currently, I am in the process of creating a Proof of Concept for Cucumber-js using TypeScript. Everything is going smoothly except for one issue - I am facing difficulties when it comes to configuring the module resolution while utilizing tsconfig-paths. ...

Encountering issues when trying to import const enums in a webpack project using babel

Currently, I am working on a react project that was initially created using create-react-app. However, we later ejected and made extensive modifications to the webpack configuration. My current struggle lies in importing const enums from external libraries ...