The error "this expression cannot be constructed" occurs when selecting dynamic properties in TypeScript

Initially, I have the following code snippet where I aim to dynamically choose a network in a straightforward manner.

import * as Ethereum from '@multiplechain/ethereum/node'
import * as Bitcoin from '@multiplechain/bitcoin/node'
import * as BinanceChains from '@multiplechain/binance-chains/node'

export enum Type {
    ETH = Ethereum.types.TransactionTypeEnum.ETH,
    BTC = Bitcoin.types.TransactionTypeEnum.BTC,
}

const networks = {
    binancechains: BinanceChains,
    bitcoin: Bitcoin,
    ethereum: Ethereum,
}

export type Options = keyof typeof networks

export const chooseNetwork = (option: Options) => networks[option]

However, whenever I attempt to utilize the code below, I encounter an error related to services.TransactionListener. Could someone assist me with this issue?

Error:

This expression is not constructable. Each member of the union type 'typeof TransactionListener | typeof TransactionListener | typeof TransactionListener' has construct signatures, but none of those signatures are compatible with each other.ts(2351) (property) TransactionListener: typeof TransactionListener | typeof TransactionListener | typeof TransactionListener

import { chooseNetwork, Options } from './multiplechain'
const chosenNetwork = chooseNetwork(data.providerConfig.code as Options)
const provider = new chosenNetwork.Provider(data.providerConfig as any)
const listener = new chosenNetwork.services.TransactionListener('ETH')

Answer №1

One possible reason for the error could be that TypeScript may not be able to ensure compatibility of TransactionListener class constructors among different network modules. To fix this issue, you can dynamically cast the network services. Check out a potential solution below:

import { selectNetwork, Keys } from './multiplechain';
const network = selectNetwork(data.providerConfig.code as Keys);
const provider = new network.Provider(data.providerConfig as any);

// Temporary workaround using 'any' type to bypass constructor signature problem
const listener = new (network.services as any).TransactionListener('COIN');

Hopefully this resolves the issue!

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

A guide to creating a JavaScript function that outputs a script in string form

Currently, I am utilizing angular and seeking to add a script to my directive's template. My goal is to create a function that can take the necessary parameters for the script and return it as a string. This approach would prevent me from having to em ...

Rendering EJS on the page even before the for loop is completed or the data is pushed to an

I'm facing a challenge where I need to display an array in HTML using EJS. However, the issue is that my EJS is rendering before any data gets pushed to the empty array, resulting in an empty array being displayed on the page. app.set('view engi ...

Struggling to make comparisons with numerical data from MongoDB in an ExpressJS route

I am currently developing a website using Node.js, EJS template, MongoDB, and Express. I am working on implementing search functionality on my page using forms, but I am encountering a small issue. The problem is related to a logical issue in the search f ...

React: Resolving issue of state becoming outdated after fetching data through a network request in the useEffect hook. Stale state no

As I work on updating and referencing the state field hasError within the initialization function of my component, it's crucial for me to control whether a redirect occurs after successful initialization or if an error is displayed. Here's a sum ...

Is there a way to convert a json array to a javascript array in AngularJs?

I am new to Angular and front-end development and facing a challenge that I can't seem to overcome. After reassigning one variable to another: $scope.testarray = $scope.todos; only the 'todos' data is being displayed when using Angular bind ...

What is the best way to achieve the functionality of this ajax jquery using vanilla JavaScript?

I am attempting to replicate this jQuery ajax POST request in Vanilla JS, which currently looks like: $.ajax({ method: 'POST', url: window.location.href + 'email', data: { toEmail: to, fromName: from, ...

Fetching dynamic JavaScript generated by PHP

I am creating a lightweight website and I have a piece of javascript code that I want to convert into a module by putting it in a separate file. This way, the code will only be loaded after a specific onClick event occurs. Successfully loading the javascr ...

Encountering an undefined property error while using Reactjs

I made an attempt to retrieve data using an ajax request, but I am uncertain about the correctness of my code. Here is the code snippet: interface IProps { data: IScheduler; } interface IState { list: IScheduler; } export default class Page extends ...

When trying to access an array directly within an object, it all too often returns as undefined

There is a React Component that has been provided with an array of objects (main_object), one of which contains another array of objects (secondary_object). Strangely, when trying to print the main object in console.log, the array is visible, but attemptin ...

What is the best way to locate an element with the class name being an email address using jQuery?

Is it possible to locate an element with an email address as the class name, considering that the email address varies? $(document).ready(function(){ //not working getting error var email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

encountering a soap error while attempting to access an ASP.NET web service

My ASP.Net test web service is operational, but I am consistently encountering 500 errors stating: "System.InvalidOperationException: Request format is invalid: text/xml. at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at System ...

Include the designated return type within a fat arrow function

No matter how hard I look, I cannot figure out the correct way to combine return type annotation with fat arrow syntax. class BasicCalculator{ value:number; constructor(value:number=0){ this.value=value; } add= (operand:number)=> ...

The initialization of Firebase is not being completed before it is being called in other files

I am currently working on a vue project and I am attempting to integrate firebase. However, I have encountered an issue where my other JavaScript files like auth.js are utilizing firebase before it is properly initialized in my main.js file (which acts as ...

Breaking down a javascript project

As the trend of splitting large JavaScript projects into separate files and then compiling them into a single distribution increases, I am eager to explore this workflow. While I have considered Node.js, npm, and Grunt for this purpose, I find the learning ...

Display the personalized list of user items on the MERN dashboard

I'm currently developing a React booking platform that interacts with my backend through a Rest API using axios and redux. My challenge now is to display personalized reservations and rooms for each user on the website. However, I'm facing an iss ...

Gathering all the indicated whole numbers from a string and placing them in an array

Upon decoding the URL query using decodeURIComponent and splitting it, the resulting array looks like this: ["pcs_availability:Online", "price:[1500 TO 1999.99]"]. I am trying to extract the proper integers from this array as shown in [1999.99]. In some ca ...

Verifying the outcome of sampling the mongoose

During my research, I encountered a roadblock. I was trying to determine if a value existed in MongoDB db collection documents using Mongoose. I had a function set up to search for a DB entry using findOne. When stripping away the unnecessary parts of the ...

When the forward button is pressed multiple times in the carousel, the alignment changes

I recently noticed that the alignment of my carousel gets disturbed when I repeatedly click the forward button (>). How can I ensure that the carousel moves smoothly one item at a time when I click the forward or backward buttons? <div class="contai ...

Using the HTTP Post method to retrieve a file object: a step-by-step guide

Is there a way to utilize a http POST request in order to retrieve a file object? Though the uploading of files to the server using the POST request seems successful and flawless, attempting to fetch the file results in an unusual response: console output ...

How can we access a value within a deeply nested JSON object in Node.js when the key values in between are not

In the nested configuration object provided below, I am seeking to retrieve the value associated with key1, which in this case is "value1". It's important to note that while key1 remains static, the values for randomGeneratedNumber and randomGenerated ...