Error message in Typescript: When a class has initialized properties, a 'super' call must be the first statement in the constructor

I am currently facing some typescript errors in my project. Would you like to see a sample of the code that is causing the issue? Here is a snippet:

module CoreWeb {
export class Controller implements IController {
    public $q;
    ...

This piece of code showcases a class that extends the controller class, among other classes.

declare var App: ng.IModule;

module CoreWeb {
    export class EntityMasterController extends Controller {
        private currenciesDataSet;
        ...

However, I have encountered an error during gulp when I attempted to initialize merchandisingConstants before calling super as shown above. The error message indicates that a super call must be the first statement in the constructor when a class has initialized properties or parameter properties. I have tried various approaches to resolve these errors but have been unsuccessful so far. Any suggestions on how I can tackle this issue?

Answer №1

When you inherit from a class, the constructor:

  1. Has to invoke super()
  2. Must be called before any other actions

In this particular scenario, all you need to do is rearrange some things:

declare var App: ng.IModule;

module CoreWeb {
    export class EntityMasterController extends Controller {
        private currenciesDataSet;
        private entity: IEntityMasterModel;
        private merchandisingConstants;
        private typeAheadOptions;

    constructor(
        $q:ng.IQService,
        $rootScope,
        $scope:ng.IScope,
        $state,
        $translate:ng.translate.ITranslateService,
        appEvents,
        commonValidationsService,
        entityDataService,
        merchandisingConstants,
        ngDialog,
        notificationsService,
        titleDataFactory
    ) {
        // Should come first
        super(
            $q,
            $rootScope,
            $scope,
            $state,
            $translate,
            appEvents,
            commonValidationsService,
            "entity",
            null,
            entityDataService,
            "name",
            ngDialog,
            notificationsService,
            "createEntity",
            "getCurrentEntity",
            "getEntity",
            "updateEntity",
            titleDataFactory
        );

        this.merchandisingConstants = merchandisingConstants;
    }

Answer №2

Here's a clever workaround I came up with to tackle this problem:

    super(
        (this.merchandisingConstants = merchandisingConstants, $q),
        $rootScope,
        $scope,
        $state,
        $translate,
        appEvents,
        commonValidationsService,
        "entity",
        null,
        entityDataService,
        "name",
        ngDialog,
        notificationsService,
        "createEntity",
        "getCurrentEntity",
        "getEntity",
        "updateEntity",
        titleDataFactory
    );

This approach uses the rather unconventional JavaScript , operator to perform an assignment as a side effect within the argument list of the function call. While any parameter could be manipulated in this way, I chose to do it with the first one. The comma operator, which is distinct from the comma used to separate arguments in a function, allows you to chain expressions together, all of which will be evaluated. However, only the last expression will determine the value of the overall expression.

By utilizing this technique, the assignment takes place while the arguments are being evaluated. So, even though the first parameter retains its original value of $q, the assignment still occurs prior to invoking the super() function.

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

Refresh required to showcase newly created items

Currently, I am developing a straightforward tool that allows users to assign budgets to teams. This tool operates in a manner similar to a standard to-do list. The delete function functions smoothly without requiring a reload. However, the create functio ...

When should you use isRequired for PropType versus defaultProps in a React application?

I often find myself confused about when to use .isRequired versus .defaultProps={...}. I personally feel that I should avoid using isRequired, as it seems like creating a potential bug in the application. By using isRequired, it automatically removes the n ...

Determine the percentage using jQuery by considering various factors

I am facing an issue with the following code snippet: <script type="application/javascript"> $(document).ready(function () { $("#market_value").on("change paste keyup", function() { var market_value = par ...

Using v-model with the Toast-UI editor in Vue.js adds a dynamic and

Is there a way to bind the input value while using toast-ui vue-editor since it doesn't support v-model? Here is my setup for toast-ui: import '@toast-ui/editor/dist/toastui-editor.css'; import { Editor } from '@toast-ui/vue-editor&apos ...

The specified instant cannot be located in 'moment' while attempting to import {Moment} from 'moment' module

Struggling in a reactJS project with typescript to bring in moment alongside the type Moment Attempted using import moment, { Moment } from 'moment' This approach triggers ESLint warnings: ESLint: Moment not found in 'moment'(import/n ...

Manipulating the DOM by nesting an icon within a button element in HTML

Currently working on my todo list project and I have a question about using innerHTML. I'm curious if I can include an icon inside of a button tag like this: btn.innerHTML = '<i class="fas fa-times fa-lg"></i>'; So, wo ...

What is the process for uploading an image file in Node.js?

var title="this is a new title"; var content="this is some unique content"; const options = { headers: {'Accept': 'text/plain', 'Content-Type': 'application/json' } }; const data = new FormD ...

Issue with updating component

Currently facing an issue with a component that utilizes the changeDetection: ChangeDetectionStrategy.OnPush The component's logic is as follows: ngOnInit(){ this.serivce.something .subscribe( evt => { // Logic to update values of the ar ...

Fade out all the other images using jQuery

I have created a jQuery code to fade images, but when I move the mouse over them all images fade simultaneously! $(".playThumb").fadeTo("normal", 1); $(".playThumb").hover(function() { $(".playThumb").each(function() { if ( $(this) != $(this) ...

Determine in Node.js if a word has been altered or has an additional letter compared to the previous word

I'm currently developing a feature for my Discord bot that allows users to play a word game. The objective is to input words that either change one letter from the previous word or add a letter. To implement this, I am utilizing the following function ...

Is it possible to transform an array of objects into a new array of objects?

After searching for a similar question, I realized none of them really addressed my issue... EDIT: My main goal is to create a reusable dropdown component where I can pass items as props directly. These items need to be objects with both a key (for the fi ...

What are the best methods for looping through ids in MongoDB and executing actions on them?

I am working with an entity object that has the following response: [ { "public": false, "_id": "5eb6da3635b1e83", "createdAt": "2020-05-09T16:28:38.493Z", "updatedA ...

``Should one prioritize the use of Generics over Inheritance, or is there a better way

We are currently in the process of implementing new contracts for our icons system, and we have encountered a debate on which approach is more preferable. Both options result in the same interface: Using Generics -> Although the interface may be less ...

The Battle: AJAX FormData vs encodeURI

When utilizing jQuery's encodeURI(), the data transmitted through AJAX appears in this format: key1=true & key2=34 & ... In order to send an image via AJAX, I employ the FormData() method, resulting in the AJAX data without an image looking ...

Finding elements based on a specific parent structure in JavaScript: A step-by-step guide

I'm currently working on a script that needs to grab content only within a specific parent structure defined as div.main-element input+label+ul. Is there a way to achieve this using JavaScript or jQuery? If anyone could point me in the right directi ...

Tips on implementing v-show within a loop

Hey @zero298, there are some key differences in the scenario I'm dealing with. My goal is to display all the items in the object array and dynamically add UI elements based on user input. Additionally, v-if and v-show function differently (as mentione ...

Exploring the values of a JavaScript promise while iterating through a for loop

I find myself wandering in the land of possibilities and would greatly appreciate some direction. After spending 2-3 hours scouring through countless SO questions and documentation related to my current predicament, I still seem to be missing the mark. Ove ...

The specified function is not recognized within the HTMLButtonElement's onclick event in Angular 4

Recently diving into Angular and facing a perplexing issue: "openClose is not defined at HTMLButtonElement.onclick (index:13)" Even after scouring through various resources, the error seems to be rooted in the index page rather than within any of the app ...

Using AngularJS, we can create a nested ng-repeat with an expression to filter the

I'm having trouble using a value from the initial ng-repeat as a filter in the nested ng-repeat. The issue lies with {{alpha.value}}. It displays correctly in the first repeat, including the filter and the h3 tag. However, in the second repeat, it s ...

AngularJS: Automatically refreshing ng-repeat based on checkbox filter updates in code

I have a container that is populated using ng-repeat="item in items | filter:isselected(item)". To filter the items, I have checkboxes with ng-model="selecteditem[$index]" and a filter function $scope.selectedItems = []; $scope.isselected = function(item ...