Merging classes from several files into a unified namespace in typescript

When working with typescript, my goal is to instantiate a class by using its name as a string. After some research, I discovered the following approach:

const googlecommand = Object.create((Commands as any)['GoogleCommand'].prototype);

This line of code exists in a separate file from where GoogleCommand is defined. It is important for "Command" to be a namespace in order for this method to work. While some resources suggest that it may be accessible through window by default, that was not the case for me. Having all "Command" classes in a single file wrapped in a namespace would simplify things, but it complicates code organization especially when dealing with multiple commands.

Therefore, my objective now is to place each command in its own .ts file and then encapsulate them within a single namespace. To illustrate, here is the conceptual structure I envision (although it will not function correctly in its current state):

// GoogleCommand.ts
export namespace {
    export class GoogleCommand extends AbstractCommand {
        ....
    }
}
// BingCommand.ts
export namespace {
    export class BingCommand extends AbstractCommand {
        ....
    }
}
// CommandProcessor.ts
import { AbstractCommand } from './AbstractCommand';
import { Commands } from './GoogleCommand';
import { Commands } from './BingCommand';    // This will obviously conflict

// The value of commandName will be determined by an external config file so its actual content 
// is unknown at this point, aside from being the name of one of the commands
let commandName;
commandName = 'GoogleCommand';
const googlecommand: AbstractCommand = Object.create((Commands as any)[commandName].prototype);
commandName = 'BingCommand';
const bingcommand: AbstractCommand = Object.create((Commands as any)[commandName].prototype);

Answer №1

To specialize your classes by their names at runtime, you can either rename them or alias them on import and create a map:

// CommandProcessor.ts
import { AbstractCommand } from './AbstractCommand';
import { Commands as GoogleCommands } from './GoogleCommand';
import { Commands as BingCommands } from './BingCommand';    

const Commands = {
   GoogleCommand: GoogleCommands,
   BingCommand: BingCommands
}

// The commandName value will come from an external config file, so its actual value is unknown here (except that it will definitely be the name of one of the commands)
let commandName;
commandName = 'GoogleCommand';
const googlecommand: AbstractCommand = Object.create(Commands[commandName].prototype);
commandName = 'BingCommand';
const bingcommand: AbstractCommand = Object.create(Commands[commandName].prototype);

The concept of using namespaces in TypeScript may not provide significant benefits according to some opinions, such as Anders who considered it a mistake.

A simpler approach would be to directly export the class.

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

There seems to be a troublesome character in the Nuxt3 production server causing some issues

When submitting an HTML encoded text to the server, everything runs smoothly on the development environment. However, once it is deployed to a Netlify server, the same request triggers a 500 error and the server side logging middleware only recognizes a PO ...

Using React JS to iterate over an array and generate a new div for every 3 items

It's a bit challenging for me to articulate my goal effectively. I have a JSON payload that looks like this: { "user": { "id": 4, "username": "3nematix2", "profile_pic": &qu ...

What is the best way to verify that all elements within an object are 'false' except for one that is 'true'?

I am working with an object that has multiple boolean fields: type SomeObject = { A: boolean B: boolean C: boolean .... } Is there a simple and efficient method to determine if all other fields (except for a specified one) are set to false? We co ...

The aggregation pipeline in nodeJS with mongoDB is failing to return any results, returning an empty array instead

Currently, I am enrolled in Jonas Schmeddtman's Node.js course where I am working on developing a tour App. However, I have encountered an issue where sending a request via Postman on the specified route results in an empty array instead of the expect ...

Customizing blockquote styling in QuillJS with a unique class

Currently, I am exploring a method to include a custom class when the user selects the blockquote toolbar button. When the blockquote is clicked, it generates the following element: <blockquote class="ql-align-justify">this is my quoted tex ...

Modifying ID styling using JavaScript on Internet Explorer

I need to change the CSS display property from none to block using JavaScript, but only for Internet Explorer. My current code is not working for the ID #backfill-image. <script> function checkForIE() { var userAgent = navigator.userAgent; ...

Include a couple of images to the jQuery Slider

I have a website and am looking to incorporate a jQuery slider that meets my needs. However, the current slider only displays 3 pictures. How can I add one or two additional pictures to the slider? Demo: http://d.lanrentuku.com/down/js/jiaodiantu-883/ He ...

Accessing a child component's method within a parent component by making a call to it

I am facing an issue where I need to invoke a method in a child component from its parent component. Here is the specific scenario: Parent Component Example // ParentComponent.js class ParentComponent extends Component { render() { ret ...

What is the most effective way to handle DOM events in Angular 8?

Looking to listen for the 'storage' event from the window in Angular 8. What is the recommended approach to achieving this in Angular? window.addEventListener('storage', () => { }); One method involves using Renderer2, but are ther ...

What reasons underlie the existence of various methods for importing Modules in JavaScript?

I'm confused about the distinctions when it comes to importing a JavaScript module in various ways such as: CommonJS ES5 ES6 NodeJS Typescript What is the reason for having multiple methods of importing JavaScript modules? Is the concept of a "modu ...

Is there a way to identify if a user originated from a Google ad and determine if this is their nth page during the session using JavaScript code?

Is there a way for me to execute specific logic when a user, who arrived at the page via a contextual advertisement, reaches a certain page during their session? How can I make this happen? ...

Unprepared for handling JSON data with JavaScript and jQuery

{ "Items": [ { "location": "bakery", "item1": "milk", "item2": "bread" } ], } Currently, I am encountering difficulties in parsing a JSON object and receiving the following error: Error: Unca ...

Tips for utilizing the "this" keyword in TypeScript

As a newcomer to TypeScript, I am seeking assistance on how to access the login service within the authenticate function. Despite using the 'this' keyword to retrieve the login service, it seems ineffective. Additionally, I find myself puzzled by ...

What exactly is the functionality of this "if" statement that operates without any operators?

I've recently started learning Javascript and I'm currently going through chapter 5 of Eloquent Javascript. In my studies, I encountered a piece of code that is puzzling to me. While I understand the general method and steps of how it works, I&ap ...

Convert HTML Tables to PDF Format

I am facing an issue with exporting my table data into a PDF using jQuery. I have made sure to install all the necessary library files, but my code doesn't seem to be working correctly. Can anyone spot any errors in my code or suggest what might be mi ...

JavaScript code that activates several hovering elements

I am a beginner in the world of JavaScript and I'm attempting to create a simple function that will activate multiple div hover effects. I have tried various approaches so far, but I believe this code is closer to the solution. Any assistance from som ...

What is the best way to generate a dummy ExecutionContext for testing the CanActivate function in unit testing?

In my authGuard service, I have a canActivate function with the following signature: export interface ExecutionContext extends ArgumentsHost { /** * Returns the *type* of the controller class which the current handler belongs to. */ get ...

Learn the art of blurring elements upon clicking in Vue

I've been attempting to trigger the blur event on an element when it is clicked, but I haven't been able to locate any helpful examples online. My initial approach looked like this: <a @click="this.blur">Click Me</a> Unfortunately, ...

What is the purpose of the c() function in JavaScript?

I recently stumbled upon some interesting JavaScript code in the source of a web page: function fsb329142055() { var b=new Array(57,50,102,50,52,99,50,53,52,56,102,98,102,98,101,102,101,49,53,61,101,99,110,57,111,78,109,54,114,111,56,48,102,38,1 ...

Customize button text in Vue using data variable conditions

There are 3 desks in a table with role IDs 2, 4, and 6. In this scenario, two tables are involved. The goal is to dynamically display a specific role name on a button based on the current user's role ID. The desired displays are: If the current use ...