Dynamically loading classes in TypeScript without using default export

Is there a way to dynamically load classes in TypeScript without using a default export method? I have managed to make it work partly, but I am looking for a solution that doesn't require a default export:

export default class Test extends Base {
...
register(new (await import(file)).default())

Edit: Thanks to Dhananjai's suggestion, I discovered this alternative approach: (parse is coming from path and I am using glob to get all paths to files in a directory)

for (const file of files) {
  try {
    const { name } = parse(file)
    const command = new (await import(file))[name]()
    this.register(command)
  } catch {
    return logger.error(`${file} is either not exporting a class or the file name does not match the exported class name`)
  }
}

Answer №1

Just make it easy by

create a new Test object that extends Base
...
and then add it to the registry with register(new (await import(file)).Test())

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 process through which Typescript determines the property types of union types?

I am implementing a unique set of types to enable angular form typing: import { FormArray, FormControl, FormGroup } from '@angular/forms'; export type DeepFormArray<T, U extends boolean | undefined = undefined> = T extends Array<any> ...

UI5 Tooling generated an error stating that "sap is not defined" after a self-contained build

Having successfully developed an application using SAPUI5 1.108, I encountered a setback when attempting to deploy it to a system running SAPUI5 version 1.71. The older version lacks certain features, causing the application to fail. In order to address th ...

The TypeScript compilation failed for the Next.js module

Working on a project using Next.js with typescript. The dev server was running smoothly, and I could see frontend changes instantly. However, after modifying the next.config.js file and restarting the server (later reverting the changes), compilation issue ...

What is the method for extracting user input from a text box on a webpage?

Having trouble with retrieving the value from a text box in my search function. SearchBar Component import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-search', templateUrl: './search.compon ...

Is there a way to verify the presence of data and halt code execution if it is not found?

In my data, there is a table containing a total of 5 links. The first 2 links can vary in availability as they are dynamic, while the last 3 links are static and are always displayed. The dynamic links' data is deeply nested within the state object, s ...

Having trouble displaying a "SectionList" in "React Native", it's just not cooperating

As a newcomer to programming, I recently started working with React Native. I attempted to create a FlatList, which was successful, but the data did not display as I intended. I realized I needed a header to organize the data the way I wanted, so I discove ...

Discover the contents of an Object's key in TypeScript

I currently have a variable of type object. let ref_schema_data: object The value of ref_schema_data: { '$schema': 'http://json-schema.org/draft-07/schema', '$id': 'tc_io_schema_top.json', allOf: [ { type: &a ...

Send a function as a parameter to another component, but it remains dormant

I am attempting to control the enable and disable state of a button based on changes in a value. To achieve this, I have defined a model as follows: export class Model{ label:string=''; isEnabled:Function=()=>true; } The component1 i ...

Utilizing the adapter design pattern in Angular with TypeScript for enhancing a reactive form implementation

I've been struggling to understand how to implement the adapter pattern in Angular6. Despite reading numerous articles and tutorials, I still can't quite grasp the concept. Could someone provide some insights on this topic? Essentially, I have a ...

Leveraging ES6 Symbols in Typescript applications

Attempting to execute the following simple line of code: let INJECTION_KEY = Symbol.for('injection') However, I consistently encounter the error: Cannot find name 'Symbol'. Since I am new to TypeScript, I am unsure if there is somet ...

Typedoc Error: Attempted to assign a value to an undefined option (mode)

After installing typedoc with the command npm install typedoc --save-dev, I proceeded to add typedocOptions to tsconfig.json: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", // ...some lin ...

Using ngFor to connect input with the Algolia Places feature

I have implemented an Algolia Places input within an ngFor loop using Angular8. The issue I am facing is that the (change) event only works properly after typing in the input for the second time. While this is functional, it's not exactly the behavior ...

Error: JSON parse error - unexpected character 'a' at index 1

I'm encountering an issue while attempting to change the album title from "cars" to "car". The error message I keep receiving is: SyntaxError: Unexpected token a in JSON at position 1. Any ideas on what might be causing this problem? Below is the cu ...

Retrieve: Type 'string | undefined' does not match the parameter type 'RequestInfo'

When using the fetch function, I encountered an error with the "fetchUrl" argument: Error: Argument of type 'string | undefined' is not assignable to parameter of type 'RequestInfo'. This is the code snippet where the error occurred: ...

Angular: Initiate multiple functions simultaneously and combine results afterwards

My current code successfully zips and saves the response of a JSON array by splitting them into individual files using a single method. zip: JSZip = new JSZip(); folder: JSZip = new JSZip(); this.apicall.api1() .subscribe( response => { for (let r ...

Divide the list of commitments into separate groups. Carry out all commitments within each group simultaneously, and proceed to the next group

My Web Crawling Process: I navigate the web by creating promises from a list of website links. These promises act as crawlers and are executed sequentially. For instance, if I have 10 links, I will crawl the first link, wait for it to complete, then move ...

Navigating to a specific section upon clicking

Imagine a scenario where there is a landing page with a button. When the button is clicked, redirection to another page with multiple components occurs. Each component on this new page serves a different function. Additionally, the desired functionality in ...

Is it considered poor practice in TypeScript to manually set the type when the type inference is already accurate?

Is it necessary to explicitly set the variable type in TypeScript when it is inferred correctly? For example: const add = (a: number, b: number) => a + b; const result = add(2, 3); // Or should I explicitly declare the return value type? const add = ...

Tips for expanding the functionality of the d3-selection module using TypeScript

I am currently working on a project that involves TypeScript and d3. I have already installed 'd3' and '@types/d3', and my use of d3 looks like this: import * as d3 from 'd3'; const x = d3.scaleLinear ... Everything was goin ...

issue TS2322: The function returns a type of '() => string' which cannot be assigned to type 'string

I have recently started learning Angular 6. Below is the code I am currently working on: export class DateComponent implements OnInit { currentDate: string = new Date().toDateString; constructor() { } ngOnInit() { } } However, I am encounterin ...