Varied types of returns in inherited classes

Let's imagine two classes, A and B. Class A sets the parameters that can be used by class B. However, when it comes to callback functions, A doesn't know what type of parameter will be passed from B. Therefore, in class A, these parameters are simply defined as Objects.

class A {

    private _on_user_selection:(selection:Object) => void = $.noop;

    set on_user_selection(fn:(selection:Object) => void) {
        if ($.isFunction(fn)) {
            this._on_user_selection = fn;
        }
    }
}

class B extends A {
    // ...
}

Class B, on the other hand, knows exactly what type of parameter to expect in its callback function. So, how can we ensure that we can use it like this:

let b = new B();
b.on_user_selection = (selection:SomeInterfaceDefindeSomewhere):void => {
    // ...
};

In this scenario, the code provided above would work perfectly fine. However, the goal is to update the return type of the callback function within class B itself, not just where it's called.

Answer №1

To create a generic version of A, you can do this:

class A<T> {
    private _on_user_selection: (selection: T) => void = $.noop;

    set on_user_selection(fn: (selection: T) => void) {
        if ($.isFunction(fn)) {
            this._on_user_selection = fn;
        }
    }
}

class B extends A<SomeInterfaceDefindeSomewhere> {
    // ...
}

It is recommended to avoid using type Object. Instead, consider using any or the new object type.

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 JQuery loading symbol does not prevent keyboard interactions

I successfully implemented a Jquery busy indicator in my application using the following link: However, I noticed that even though it prevents users from clicking on input elements while loading, I can still navigate to these elements by pressing the tab ...

Updating @Html.DisplayFor item following a successful ajax request

Attempting to update a value on my view, I seem to have the correct path, but the update only occurs when I reload the entire view. Here is the HTML: <table class="table"> <tr> <th> @Html.DisplayNameFor(model =&g ...

Immediately refresh the page after successfully loading the DOM through JavaScript

function selectDate(){ var d=document.getElementById("selecter").value; alert(d); var days=['Monday','Tuesday', 'Wednesday','Thursday', 'Friday', 'Saturday', 'Sunday']; / ...

Utilizing SetInterval for dynamically changing the CSS background image URL

I'm starting to feel frustrated with this situation... I have a solution where the CSS background is coming from a webservice. Currently, the system refreshes the entire page using HTML: <meta http-equiv="refresh" content="300" /> ... body { ...

Accepting insecure certificates in Chrome with Selenium-Webdriver in JavaScript: A Step-by-Step Guide

After generating a test script using Selenium-IDE in Javascript-Mocha format, I encountered an issue with an insecure certificate when trying to access a remote URL locally. To address the problem, I need to modify the generated TestScript to include Chro ...

Error message encountered in Typescript eslint: File extension "ts" is missing in import statement for the specified file

I am encountering an issue with my Node/Express application created using Typescript. The problem lies in eslint throwing an error that says: Missing file extension "ts" for "./lib/env" import/extensions Below is the content of my .eslintrc file: { ...

Using jQuery to modify the CSS of a div located outside of an iframe

Currently, I am developing a straightforward script. Firstly, here is all of the code that I have: <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script type="text/javascript"> function SuperWebF1() { $("#outerd ...

The directive subscription remains inactive even when the subject triggers the next function

Plunkr: https://plnkr.co/edit/KfPfVSbZm087uIPvFEkM?p=preview I have developed a service that serves as an API for a modal component. In addition, there is a directive available that can be used to apply a class to any element when the modal is open. Howev ...

Encountering issues while attempting to modify the route from a particular Component

I have encountered an issue with changing routes in React from a specific component to another. Switching between '/' and '/login' works fine, but when the active route is '/menu-management', clicking on the Link causes an err ...

Angular 6 - Issue: Unable to retrieve the value of an undefined property

I'm a beginner when it comes to Angular and Typescript, and I'm facing an issue with this console error: "ERROR TypeError: Cannot read property 'value' of undefined" Despite successfully calling a service that fetches Chuck Norris joke ...

Switching between two HTML files on jQuery Mobile pages

My goal is to create a simple website with two key pages - "Search" and "Results". Initially, I had a multi-page template set up that worked fine. However, I encountered an issue when I wanted to load the results page without having to go back to the searc ...

Ensuring the validity of multiple email fields

I am utilizing a validation script created by Joren Rapini for my online form. Visit Joren's Website for more information. The current code allows me to validate one email address, but I need to validate two different email fields in the form. Does a ...

"Embrace the powerful combination of WinJS, Angular, and TypeScript for

Currently, I am attempting to integrate winjs with Angular and TypeScript. The Angular-Winjs wrapper functions well, except when additional JavaScript is required for the Dom-Elements. In my scenario, I am trying to implement the split-view item. Although ...

How can I navigate through a webpage using Selenium WebDriver and JavaScript?

Currently, I am utilizing the JavaScript API for selenium-webdriver and my goal is to scroll/move down a page in a gradual manner to facilitate visual inspection. Although I am aware that the code below will direct me immediately to a link at the end of t ...

The request sent by Node Express is directed to a different endpoint within the router

I am struggling to understand why my request: localhost:3000/api/customers/search?q=glenn Is being directed to: // Retrieve a single Customer with customerId router.get("/:customerId", customers.findOne); Rather than the intended destination: // S ...

Customize the background colors for events in the jQuery weekcalendar plugin to distinguish between different types of activities

I recently started using the jQuery weekcalendar plugin to display a web-based calendar with appointments. The CSS code below is used to set the color of all events: .wc-cal-event { background-color: #00BFFF; font-size: 0.8em; position: absolu ...

Creating keys for my console.log data and appending it to html in order to display console log results in textboxes

I am currently developing a matching system for Player vs. Player battles and I need to ensure that the keys are appended correctly to my div element. Previously, I have successfully used append with keys before. Below is the code snippet: ...

Using PHP to pass data to JavaScript via jQuery

I'm currently facing a challenge where I need to transfer a PHP variable from one PHP file to a separate JavaScript file. The variables that I am trying to pass are located at the end of the PHP file within the input functions, and they need to be ass ...

Navigating through JSON arrays can be achieved by utilizing iteration techniques

I'm having trouble with a script and can't figure out how to make it display in the designated div. It may have something to do with how I'm handling the response. In Chrome devtools, the response looks like this: { "[\"record one& ...

Error: the function is not defined, therefore the variable is being passed

I'm attempting to pass a variable in the URL in order to automatically check a radio button on a different page depending on which link is clicked. However, I keep encountering an "Uncaught ReferenceError: radio_onload is not defined" error. Could th ...