Is it impossible to extend a Typescript class with an overriding method that uses a different parameter?

I am currently working on a Typescript MVC app and encountering an issue. When I try to extend my BaseController and override the ajaxMethod with different parameters, my transpiler throws an error. Any help would be appreciated.

Below is the code snippet:

interface i_Controller {
    ajaxMethod;
    ajaxSuccessListener;
    ajaxErrorListener;
}

class BaseController implements i_Controller {
    protected baseProperty: boolean;

    constructor() {
        this.baseProperty = true;
    }

    public ajaxMethod() {
        $.when(
            $.ajax({})
        ).then(
            this.ajaxSuccessListener,
            this.ajaxErrorListener
        )
    }

    public ajaxSuccessListener(data, status, jqXHR) {
        console.log('ajax success');
        console.log(data);
    };

    public ajaxErrorListener(jqXHR, status, error) {
        console.error('ajax error');
        console.error(status);
    };
}


class Page_1_Controller extends BaseController {
    private localProperty: number;

    constructor(input) {
        super();
        this.localProperty = input;
    }

    public ajaxMethod(someProperty) {
        /*
        /* Error:(39, 7) TS2415:Class 'Page_1_Controller' incorrectly
        /* extends base class 'BaseController'.
        /* Types of property 'ajaxMethod' are incompatible.
        /* Type '(someProperty: any) => void' is not assignable to 
        /* type '() => void'.
        */
        $.when(
            $.ajax({
                data: {properties: someProperty}
            }),
            $.ajax({})
        ).then(
            this.ajaxSuccessListener,
            this.ajaxErrorListener
        )
    }

    public ajaxSuccessListener(responseAjaxRequest_1, responseAjaxRequest_2) {
        console.log('ajax success');
        let data_1 = responseAjaxRequest_1[0];
        let data_2 = responseAjaxRequest_2[0];
        console.log(data_1);
        console.log(data_2);
    }
}

class MyApp {
    private controller: i_Controller;

    constructor() {
        this.controller = new Page_1_Controller();
        /*
        /* Error:(72, 27) TS2346:Supplied parameters do not match any
        /* signature of call target.
        */
        this.controller.ajaxMethod();
    }
}

Currently unsure why extending my classes is causing issues. Overwriting constructors and listeners works fine, so why not the ajaxMethod?

Answer №1

The error message clearly indicates that the signatures of the two ajaxMethod() functions are not compatible.

When Page_1_Controller extends BaseController, the type of ajaxMethod() becomes () => void. So, if you down-cast an instance of Page_1_Controller to BaseController, it should work with that signature.

Consider the following example:

function foo(c: BaseController) {
  c.ajaxMethod()
}
const page1 = new Page_1_Controller()
foo(page1)

Your code will fail in this scenario. The compiler points out this issue so you can catch it during compile time.

To resolve this problem, you can handle it like so:

class Page_1_Controller extends BaseController {
  ajaxMethod(someProperty?) {
    if (someProperty) {
      ...
    }
    else {
      super.ajaxMethod()
    }
  }
}

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 function of the 'Class' attribute is not functioning properly

I am currently working on a search field with a drop-down menu that determines the type of data being searched. This, in turn, dictates the input type for the search field. For example, if I am searching by "name" or "ID number", the input type is set to t ...

straightforward multiple second timer

I have multiple <span class="timer">342</span> elements with different values (in seconds). I am trying to create a countdown timer for all of them by using the following code: $('.timer').ready(function() { ...

The expiration period set in expireAfterSeconds doesn't seem to be functioning as expected in the time-to-live (ttl) configuration. Rows are

Can you please take a look at my code and provide some feedback? The issue I am facing is that the record is getting deleted without specifying the number of seconds. I have tried changing from createIndex to ensureIndex but it's still not working as ...

Implementing file change detection using view model in Angular

When using the input type file to open a file and trigger a function on change, you can do it like this: <input type="file" multiple="multiple" class="fileUpload" onchange="angular.element(this).scope().fileOpened(this)" /> The functi ...

Exploring Twig variables in Node.js with the node-twig package

Despite following the documentation meticulously, and experimenting with various methods, I am still unable to achieve success. I have attempted using the code snippet below, trying to reference the variable in the main file like this: // None of the opti ...

Error handling in angularJS can be quite challenging at times,

Currently, I am experimenting with AngularJS to develop an application, and I have encountered a challenge related to the $scope context. This is the main file of my app: var app = angular.module('app', [ 'matchCtrl', &apos ...

Access-Control-Allow-Origin header not being sent by ExpressJS

In the midst of my project, I find myself needing an angular web application to connect with a node/express backend. Despite trying to implement Cors for this purpose, the express server refuses to send the Access-Control-Allow-Origin header. I am perplexe ...

Adding types to computed properties in Vue 3's Composition API is a seamless process

Having an issue where I am trying to add type to computed but keep encountering this error: Overload 1 of 2, '(getter: ComputedGetter<AuthFormType>, debugOptions?: DebuggerOptions | undefined): ComputedRef<AuthFormType>', gave the fol ...

Acquire key for object generated post push operation (using Angular with Firebase)

I'm running into some difficulties grasping the ins and outs of utilizing Firebase. I crafted a function to upload some data into my firebase database. My main concern is obtaining the Key that is generated after I successfully push the data into the ...

Incorporate a fontawesome icon into a dynamically created button using ajax

Is it possible to insert fontawesome icons into a button created using this code snippet? $.each(response, function (i, item) { trHTML += '<tr><td>' + item.name + '</td><td>' + "<input type='button&apo ...

I am looking to have three rows of input text area comments instead of just one

Utilizing Bootstrap 4.3.1 with React Components I currently have this image: https://i.sstatic.net/rudsE.png And I am aiming for this design: https://i.sstatic.net/VmyTW.png comments: { elementLabel: "Comments", elementType: 'textar ...

Empty placeholder image appearing at the beginning of JavaScript slideshow in Ruby on Rails

As a newcomer, I ask for your understanding if I lack knowledge in some areas. I have been working on a project and using the cycle2 plugin successfully to create a slideshow on my index page with images pulled from the internet. Now, I am trying to impl ...

Achieving dynamic HTML element addition through JavaScript while maintaining their record in PHP

There is an input box where the user specifies the number of new DIV elements to be added dynamically. This request is then sent to PHP via Ajax, where it prepares an HTML DIV with some inner input tags. Each DIV has a unique id attribute generated increme ...

Is it possible to integrate a Backbone app as a component within a separate app?

I am currently in the process of familiarizing myself with Backbone.js and front-end development, as my background is more focused on back-end development. I have a question related to composition. Imagine that I need to create a reusable component, like ...

Compile Node.js applications for multiple projects using Grunt

I am looking for an efficient way to build a multi-project application. Currently, my project structure looks like this: Each app is a nodejs application - parent folder (git root) |- app1 |-- app1-backend |-- app1-frontend |- app2 |- app3 Right now, I ...

Adjusting body styles in a NextJS application using localStorage prior to hydration: A step-by-step guide

If you visit the React website and toggle the theme, your choice will be saved in localStorage. Upon refreshing the page, the theme remains persistent. In my NextJS project, I am attempting to achieve a similar outcome by applying styles to the body eleme ...

What could be causing the error message "CSRF token missing or incorrect" to appear?

I am facing an issue with returning a value from a View function in Django. This particular function is called from a JavaScript code using Ajax, but I'm encountering an error that says 'Forbidden (CSRF token missing or incorrect)'. JavaScr ...

Tips for checking the validity of PHP variable names, such as $as['abc'], within an HTML textbox

Can anyone assist me with validating a user input PHP variable name such as $as_cap['abc'] during insertion? I need to verify if the format of the variable name is correct or incorrect. Currently, I am using eregi("^[a-z0-9_.'-]{1,50}$") ...

Custom attribute in ReactJS component - I am not defined in my custom attribute in React component

I am currently working with ReactJS and I am facing an issue regarding accessing a custom attribute -name- of my ReactJS component. Despite trying to use e.target.name, it keeps returning "undefined" on my console. I cannot seem to figure out why this is ...

The modal in Bootstrap V5 refuses to hide using JavaScript unless the window method is utilized

Currently in the process of developing a react application and utilizing standard bootstrap. The command to display a modal and switch to one is functioning properly; but, the command to hide the modal does not work unless I establish it as a property on t ...