You must use the 'new' keyword in order to invoke the class constructor

Although similar questions have been asked before, my situation differs from the typical scenarios. I have a basic base class named CObject structured as follows:

export class CObject extends BaseObject {
    constructor() {
        super();
    }
    static url(path: string): string { return ""; }
    static wssUrl(): string { return ""; }
    static callMethod(method, path: string, params: any, noConvertData?: boolean): Promise<any> { return null; }
    static post(path: string, params: any, noConvertData?: boolean): Promise<any> {
        return CObject.callMethod('post', path, params, noConvertData);
    }

    // other methods...

}

The issue arises when I extend a class from CObject and attempt to instantiate it. Interestingly, instantiating CObject alone poses no problems. However, derived classes trigger an error, even if they are empty like this:

export class TestClass extends CObject {
    constructor() {
        super();
    }
}

This code is used on both the server (Node.js) and client sides. Strangely, it functions without errors on the server side but fails on the client side. Upon inspecting the generated babel code, everything seems normal except when calling the CObject constructor in derived classes.

Frustratingly, after days of troubleshooting, I can't seem to resolve the issue. Your assistance would be greatly appreciated. Thank you.

Answer №1

Big shoutout to Oscar Paz for helping me pinpoint and resolve the issue I was facing. It turns out, the problem stemmed from my ATL configuration:

"awesomeTypescriptLoaderOptions": {
    "babelrc": true,
    "useBabel": true,
    "useWebpackText": true,
    "useTranspileModule": true,
    "doTypeCheck": true,
    "forkChecker": true,
    "presets": ["env", { "targets": "last 2 versions, ie 11", "modules": false }, { "exclude": ["transform-es2015-classes"] } ],
    "babelOptions": {
        "sourceMaps": true
    },
    "useCache": true
}

Specifically, the line causing trouble was:

    "presets": ["env", { "targets": "last 2 versions, ie 11", "modules": false }, { "exclude": ["transform-es2015-classes"] } ],

Even though I had included:

    "babelrc": true,

I expected .babelrc to be utilized as it was in the Node.js code segment. However, this led to dual definitions (ES6 and ES5) of classes derived from CObject, resulting in an error. The generation of CObject and initial ConfigSection definition seemed fine:

let CObject = exports.CObject = class CObject extends _BaseObject.BaseObject {} ...
let ConfigSection = ConfigSection_1 = class ConfigSection extends Shared_Core_CObject__WEBPACK_IMPORTED_MODULE_1__["CObject"] {} ...

However, further down the line:

var ConfigSection = ConfigSection_1 = function (_CObject) {
    (0, _inherits3.default)(ConfigSection, _CObject); ...

This snippet was where things went awry. I'm puzzled as to why ATL did not disregard those options and why they triggered such code-generation discrepancies. Maybe someone more knowledgeable can provide insight.

Answer №2

Attention Google employees, here's another reason for encountering this error: In April 2019, the utilization of the now unsupported why-did-you-update npm React module resulted in this issue.

The bug was resolved by removing the module and its implementation.

Answer №3

After some investigation, it became clear that the removal of semi-colons from the end of lines within the require() statement (especially right before an IIFE) was causing the problem at hand.

const MyClass = require("./myclass")

(() => { ... code ... })()

Upon adding back the semi-colons at the end, the issue resolved itself. Your mileage may vary.

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

The system is unable to locate the specific file or directory that is causing an error in the Pug

After deploying to Heroku, I encountered an error that was not present when running the application locally. Here is the message displayed in the browser: https://i.stack.imgur.com/CbhaV.png This is my display.pug file: extends ../LoginLayout/LoginLayou ...

Exploring the power of Next.js, Styled-components, and leveraging Yandex Metrica Session Replay

I'm currently involved in a project that utilizes Next.js and styled-components. In my [slug].tsx file: export default function ProductDetails({ product }: IProductDetailsProps) { const router = useRouter(); if (router.isFallback) { return ( ...

The Angular application has encountered a stack overflow due to exceeding the maximum

./src/main.ts - An issue occurred: The module build process failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js): Error: Maximum call stack size exceeded import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; { App ...

Utilize ModifyDOM to erase text triggered by selecting a radio button

I have created a form that includes four radio buttons along with a reset button to clear the form. When a radio button is selected, information is displayed using "displayText". I am looking to add an onclick handler to trigger a function that will delete ...

Issue with jquery's .load() and getScript functions

Earlier today, I encountered an issue with a .load() function being called in a script. I managed to solve the problem using .getScript(), but now I'm facing a major issue - the function is being executed multiple times. You can find the full code a ...

Can CSS be used to automatically focus on a div element?

Can CSS be used to set autofocus on a div element? <div class="form-group" style="margin-left:10px"> <label for="organizationContainer" class="nmc-label">@Res.GroupStrings.CreateNewGroupOrganization</label> <div id="organiza ...

What are the available search options in the MarkLogic Search API to limit keyword searches from including specified values within JSON properties?

Is there a way to limit the MarkLogic search API keyword search so it does not include specific JSON property values? For example, can I search for keyword 'x' in all properties of JSON documents except for those with values of 'p', &ap ...

Can we add to the input field that is currently in focus?

Recently, I've been working on a bookmarklet project. My goal is to append an element to the currently focused input field. For instance, if a user clicks on a textarea and then activates my bookmarklet, I want to insert the text "Hello" into that sp ...

Submit a collection of images and an object to the server using ReactJS

I'm currently working with Reactjs on the frontend. In order to set the profile picture to state, I've implemented the following code: handleImageChange = (event) => { event.preventDefault(); var file = event.target.files[ ...

Javascript error: attempting to access property value of a null object

Is there a way to access the value of 'nilai' ID in a different function? var sis = 'SELECT nis, nama_siswa FROM nilai_tugas'; connection.query(sis, function(err, rows, cols) { if(err){ console.log ...

Configuring multiple ports with SSL certificate for a single domain name on NGINX

I have developed a website that relies on a Rest API to fetch all its data. The website is secured with an SSL certificate. Here is how my default file (etc/nginx/sites-enabled/default) is structured: server { listen 80; server_name example.com; ...

Exploring ways to check async calls within a React functional component

I have a functional component that utilizes the SpecialistsListService to call an API via Axios. I am struggling to test the async function getSpecialistsList and useEffect functions within this component. When using a class component, I would simply cal ...

Can you explain the working mechanism behind mongoose.connect(connectionSring)?

Having a background in Python where I connected to databases and executed SQL without an ORM using the cx_Oracle library, my approach was similar: >>> conn = cx_Oracle.connect(connectionString) >>> curs = conn.cursor() >>> _ = c ...

Tips for accessing the PR number in a Node.js GitHub Probot listening for the `pull_request` event

I've recently developed a GitHub probot application using nodejs and typescript. Currently, I have set up an event listener for the pull_request event. How can I extract the pr_number from the context object within the probot? The snippet below is fr ...

Having trouble configuring the mailgun key and user name settings

I currently have Mailgun settings stored in my database. I need to ensure that the Mailgun Client key, username, and email are fetched from the database before any emails are sent to the client. However, I am facing issues with setting this data. The from: ...

Steps to ensure that MongoClient is accessible globally on all pages within a Node.js REST API

After researching the official MongoDB documentation, I have successfully integrated mongoDB into my NodeJS REST API using the following connection code. const { MongoClient } = require("mongodb"); // Connection URI const uri = "mongodb+s ...

What is the reason for needing to restart the Next.js dev server in order to view changes?

Recently, my experience working on a particular Next.js project took a turn for the worse. Changes that used to show up automatically in the browser stopped appearing. Despite trying to refresh the page, nothing seemed to work—I had to shut down the deve ...

Making a Cross-Origin Resource Sharing (CORS) request with jQuery utilizing the $

I am currently in the process of building a web application that relies heavily on data from multiple domains. Approximately 90% of the requests made by my application are cross-domain requests. However, I have encountered an issue where I am unable to re ...

Enhancing OpenSeadragon images with custom overlays and managing error messages

Currently, I am experimenting with the Basic Single-Row Tile Source Collection example using the same configurations and tile sources outlined in the example. However, I am encountering difficulties in adding overlays to the first and second images as int ...

Can we set a specific length for an array passed in as a prop?

Can we use Typescript to specify the exact length of an array coming from props? Consider the following array of objects: const sampleArray = [ { key: '1', label: 'Label 1', value: 9 }, { key: '2', label: 'Label 2&ap ...