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

I am looking to transfer the value of one textbox to another textbox within a dynamic creation of textboxes using JavaScript

var room = 1; function add_fields() { room=$('#row_count').val()-1; room++; var objTo = document.getElementById('education_fields'); var divtest = document.createElement("div"); divtest.setAttribute("class", "form- ...

Discover the art of utilizing two distinct binding strings, wherein upon the selection of either, the alternate binding string shall automatically be

Having to use two different bindingstrings is a requirement due to a tool used for creating PDFs. My objective is to have the corresponding bindingstring turn "Off" when a user clicks on either the Yes or No button, and have the clicked button turn to "Yes ...

Tips for updating Nodejs' module dependency to a newer version

Currently, my project utilizes the react-cropper library which includes version cropper ^0.10.0. However, I require certain methods from cropper version 0.11.1. To address this issue, I decided to fork the project to my own GitHub repository in order to up ...

Assign the values from the axios response to variables within the exported const

Currently, I am incorporating axios into my vue.js application to perform an HTTP POST request and retrieve some variables for a vue-echart. However, I have encountered a bit of a roadblock in determining the most effective approach. The snippet below is ...

Error message stating: rxjs and firebase encountered a TypeError when attempting to add property 0 because the object is not

My angular application interacts with firebase firestore as the backend database. I am working on a function to retrieve document snapshots from firestore in a generic way. Here is the code snippet where I encounter an error: /** * Get a 'liste ...

Display PDF blob in browser using an aesthetically pleasing URL in JavaScript

Using Node, I am retrieving a PDF from the server and sending it to my React frontend. My goal is to display the PDF in the browser within a new tab. The functionality works well, but the URL of the new tab containing the PDF is not ideal. Currently, the U ...

Insert the variable into the specified div ID

I am looking to implement an incremental div id system to ensure all my ids are unique. This way, I can make use of jQuery effects to customize them individually. Let me know if you need further clarification on my query. div id ="name_$id" Perhaps I sh ...

Update the content of a div and refresh it when a key on the keyboard is pressed

I need to hide the images in a div when I press a key on the keyboard. How can I achieve this? <div> <span role="checkbox" aria-checked="true" tabindex="0"> <img src="checked.gif" role="presentation" alt="" /> ...

Improving the Roman Numeral Kata with JavaScript

As a newcomer to the world of coding, I have taken on the challenge of mastering the Roman Numeral Kata using Javascript. I am pleased to report that all the specifications are passing successfully. After refactoring the spec file, I am now focusing on re ...

The JSON parsing functionality is not working as expected in my app.js file

app.js: const express = require("express"); const https = require("https"); const app = express(); const port = 3000; app.get("/",function(req,res){ const url ="https://maps.googleapis.com/maps/api/geocode/jsonaddress=1600+Amphitheatre+Parkway,+Mounta ...

Methods for updating the value of a `<select>` element in an AngularJS controller

Within my HTML code, I have a select element with options ranging from 1 to 10: <select id="selVal" ng-model="product.quantity" ng-options="o as o for o in quantityValues" ng-change="updateDelta(product.quantity, {{product.quantity}}, product.selec ...

Hide the Modal Content using JavaScript initially, and only reveal it once the Onclick Button is activated. Upon clicking the button, the Modal should then be displayed to

While trying to complete this assignment, I initially attempted to search for JavaScript code that would work. Unfortunately, my first submission resulted in messing up the bootstrap code provided by the professors. They specifically requested us to use Ja ...

Changing the bootstrap popover location

I'm looking to customize the position of a Bootstrap popover that appears outside of a panel. Here's my setup: HTML: <div class="panel"> <div class="panel-body"> <input type="text" id="text_input" data-toggle="popover ...

PHP function with JSON response encountered an error during the AJAX call

I am currently working on creating a News Ticker that utilizes PHP, Javascript, and AJAX. The first step involved creating a PHP function called getFeed(), which gathers data from various news websites into an Array. This data is then returned in JSON form ...

Unveiling and Shifting Among Concealed HTML Forms

After going through numerous tickets with similar questions, I still can't seem to achieve what I want. So, I have no choice but to ask this question myself. I currently have an HTML page with 2 forms and 2 buttons. Both forms are initially hidden us ...

Using Angular 2: A Beginner's Guide to Navigating with the Latest Angular 2.0.0-rc.1 Router

As I embarked on a new Angular 2 project, I was puzzled to discover that I inadvertently installed two different versions of the angular router: "@angular/router": "2.0.0-rc.1", "@angular/router-deprecated": "2.0.0-rc.1", Despite my best efforts, I co ...

The canvas grid is malfunctioning and failing to display correctly

My current code allows me to draw a grid on a canvas with multiple lines, but I'm encountering an issue when trying to render 25 or more lines - some of them don't appear on the canvas. This problem becomes more noticeable when there are 40 or mo ...

What is the best way to remove the hover effect from a specific element within a div?

I am looking to achieve a specific hover effect where the white part does not darken when hovering over a certain element within its child elements. Here is the HTML code I have: <div className= {css.searchBarDiv}> <div className={css.searchBar ...

Postponing the execution of a controller until all JSON files have been fully loaded

I am currently trying to grasp the concepts of AngularJS, so my question might not be perfect. Is it feasible to delay the execution of a controller until the json files are fully loaded in a separate function? Below is the controller code: app ...

Vue component updating its model only upon input element losing focus

I'm a beginner with vue and I'm currently working on incorporating an ajax search feature that triggers when a keyup event occurs. I have noticed that the model only updates when the input element loses focus. Sample HTML Code: <input name=" ...