Generating instances of classes using variables in Typescript

Are there methods to modify the below piece of code in order for it to be compatible with Typescript?

public shops: string[] = [
   "AShop",
   "BShop",
   "CShop",
];    

this.shops.forEach((shop, index) => {
    let instance = new window[shop](index);
    this.instances.push(instance);
});

The current method is not functional with Typescript due to the absence of window within the scope. It cannot be compiled under these circumstances. (Even though it is effective with vanilla JS)

How can the variable name shop within the loop be treated as an expression to generate a dynamic class from it?

Answer №1

Give this a shot:

const stores: string[] = ["StoreA", "StoreB", "StoreC"];

class BaseStore {
    public constructor(index: number) {
        console.log(index);
    }
}

class StoreA extends BaseStore {}
class StoreB extends BaseStore {}
class StoreC extends BaseStore {}

interface StoreConstructor {
    new (index: number): BaseStore;
}

interface Window {
    StoreA: StoreConstructor;
    StoreB: StoreConstructor;
    StoreC: StoreConstructor;
    [store: string]: StoreConstructor;
}

window.StoreA = StoreA;
window.StoreB = StoreB;
window.StoreC = StoreC;

const instances: BaseStore[] = [];

stores.forEach((store: string, index: number) => {
    let instance = new window[store](index);
    instances.push(instance);
});

console.log(instances);

Answer №2

This structure is quite unique because it presents a challenge when it comes to achieving proper type checking at compile time due to the dynamic classes in the global scope. One possible solution could be to simply use <any> and move on. However, if you require specific type guarantees for the resulting instance, it's recommended to explicitly specify them using variable types or casting:

this.shops.forEach((shop, index) => {
    let instance = new (<any>window)[shop](index);
    this.instances.push(instance);
});

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

`Is it possible to integrate npm libraries with typescript and ES6?`

I am looking to focus on using ES6 as the output for a node server-side app that I plan to run on the cutting-edge iojs distribution, which hopefully has support for the latest ES6 syntax. However, I'm unsure about how to integrate standard NPM libra ...

Transformation of Ionic 2 ScreenOrientation Plugin

Can someone assist me with this issue? A while back, my Ionic 2 app was functioning correctly using the ScreenOrientation Cordova plugin and the following code: window.addEventListener('orientationchange', ()=>{ console.info('DEVICE OR ...

Having issues with Angular material autocomplete feature - not functioning as expected, and no error

I have set up my autocomplete feature, and there are no error messages. However, when I type something in the input field, nothing happens - it seems like there is no action being triggered, and nothing appears in the console. Here is the HTML code: ...

Angular fails to show route after successful login

Within my application, I have divided it into two areas: the admin area (referred to as iwti) and the 'retaguarda' area. The 'retaguarda' section is functioning correctly, but when I navigate to the route /iwti, the layout within the &l ...

Is it possible to simultaneously update two entities using a single endpoint?

In order to update data in two different entities with a @OneToOne relationship between UserEntity and DetailsEntity, I need to create a function in my service that interacts with the database. Here are the entity definitions: UserEntity @Entity() export ...

Error: The function setIsEnabled does not exist

Currently, I am in the process of merging two separate next.js projects to create a website that can utilize the Cardano wallet 'Nami'. The code for accessing the wallet functions correctly in its original project, but when transferred over, it p ...

I must remove the thumb from the input range control

I am looking for a way to remove the thumb from the progress bar in my music player. I have tried various methods without success, and I simply want the progress bar to move forward with color change as it advances based on the Progress variable. For refe ...

Learn the process of adjusting the Time Zone in Angular2-HighCharts!

I've been struggling for a few days now trying to adjust the UTC time in an area chart using Angular2-HighCharts. The backend API is returning timestamps which I then inject into the chart, but each time it's being converted to "human time" with ...

What is the best way to modify the underline style of a tab in Material UI?

I'm trying to customize the underline of: https://i.stack.imgur.com/J2R1z.png Currently, I am using material ui version 4.12.3 The code snippet for generating my tabs is below: function renderTabs(): JSX.Element { return ( <Tabs className={cla ...

Downloading a PDF in a Next.js application

How can I add a button or link that will instantly download my PDF portfolio when clicked? I am currently working on my resume section and would like to provide users with the option to easily download my CV. Is there a way to do this, and if so, how can ...

Implementing tailwindcss styles in a typescript interface with reactjs

In my code, I have a file named types.ts that defines an interface called CustomCardProps. I pass this interface to the CustomCard component within the home.tsx file. Additionally, I have a folder named constant with an index.ts file where I store values o ...

When a class decorator is returned as a higher-order function, it is unable to access static values

Check out this showcase: function Decorator(SampleClass: Sample) { console.log('Inside the decorator function'); return function (args) { console.log('Inside the high order function of the decorator: ', args); let sample = ...

Methods for resolving a ViewStyle typescript issue in react native

Trying to pass a width parameter into StyleSheet is causing an error like this: <View style={styles.children(width)}>{children}</View> Here's how I'm trying to use it: const styles = StyleSheet.create({ modalContent: { flex: ...

Managing Observable<Person[]> in ng-bootstrap typeahead instead of Observable<string[]>: a complete guide

I'm new to Angular/Typescript and have a question. I recently tried out the example from Wikipedia in ng-bootstrap typeahead. Instead of using the Wikipedia call, I decided to use a custom REST service that has the following GET endpoint: GET /pers ...

NodeJS on Cloudlinux requires that the node modules for applications be stored in a distinct folder (virtual environment) designated by a symbolic link known as "node_modules"

I recently encountered an issue while trying to deploy my Nodejs/TypeScript web application on my cpanel shared hosting. The error I received stated: * Cloudlinux NodeJS Selector requires the node modules for the application to be stored in a separate f ...

Guide to developing a personalized useReducer with integrated decision-making and event activation

I am interested in creating a custom hook called useTextProcessor(initialText, props). This hook is designed for managing and manipulating text (string) within a React state. It utilizes useReducer to maintain a cumulative state. Here is the implementation ...

angular directive to receive an object

When I have a table and click on a row, the information is supposed to be displayed in a different component using the @input decorator. However, instead of displaying the correct result in my other component, I am getting [object Object]. table.html < ...

When a checkbox is clicked, how can we use Angular 4 to automatically mark all preceding checkboxes as checked?

I have a series of checkboxes with labels such as (Beginner, Intermediate, Advanced, Expert, etc.). When I click on any checkbox, I want all previous checkboxes to be checked. For example: If I click on Advanced, only the preceding checkboxes should get ...

What is the best way to access a component's data within its method using Vue and Typescript?

Starting a Vue.js project with TypeScript and using single file components instead of class-styled ones has been my goal. However, I have encountered a recurring issue where I get error TS2339 when trying to reference my components' data using the "th ...

Creating a setup with Angular 2+ coupled with Webpack and a Nodejs

I have successfully configured Angular2+webpack along with NodeJs for the backend. Here is a basic setup overview: webpack.config.js: var webpack = require('webpack') var HtmlWebpackPlugin = require('html-webpack-plugin') var Extract ...