Unable to attach eventName and callback to addEventListener due to the error message stating 'No overload matches this call'

I am attempting to attach an event listener to the input element stored within a class method. This method takes a props object containing eventName and callback.

public setTextFieldInputListener({ eventName, callback }: TextFieldListenerProps): void {
    this.input.addEventListener(eventName, callback);
}

The props object for the listener is a union type of two interfaces: BlurTextFieldCallbackProps and InputTextFieldCallbackProps

export type TextFieldListenerProps = BlurTextFieldListenerProps | InputTextFieldListenerProps;

export interface BaseTextFieldListenerProps {
    eventName: Extract<keyof GlobalEventHandlersEventMap, 'blur' | 'input'>;
    callback(e?: FocusEvent | Event): void;
}

export interface BlurTextFieldListenerProps extends BaseTextFieldListenerProps {
    eventName: Extract<keyof GlobalEventHandlersEventMap, 'blur'>;
    callback(e?: FocusEvent): void;
}

export interface InputTextFieldListenerProps extends BaseTextFieldListenerProps {
    eventName: Extract<keyof GlobalEventHandlersEventMap, 'input'>;
    callback(e?: Event): void;
}

When I attempt to assign the eventName and callback, I encounter this error:

TS2769: No overload matches this call. Overload 1 of 2, '(type: "input" | "blur", listener: (this: HTMLInputElement, ev: Event | FocusEvent) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error. Argument of type '((e?: InputEvent | undefined) => void) | ((e?: FocusEvent | undefined) => void)' is not assignable to parameter of type '(this: HTMLInputElement, ev: Event | FocusEvent) => any'. ...

Initially, I thought there might be an issue if eventName was `'blur'` and the event was a FocusEvent. So, I created a typeguard:

export function isBlurTextFieldProps(value: BaseTextFieldListenerProps): value is BlurTextFieldListenerProps {
    return value.eventName === 'blur';
}

I then modified the method responsible for setting the event listener:

public setTextFieldInputListener(listenerProps: TextFieldListenerProps): void {
    if (isBlurTextFieldProps(listenerProps)) {
        this.input.addEventListener(listenerProps.eventName, listenerProps.callback);
    }
}

However, this did not resolve the issue :/

My question is:

  • Why am I encountering this error?
  • How can I resolve it while maintaining strong types? (I am aware that using any could fix this, but it's not my preferred approach)

Answer №1

To accomplish this task, you can utilize the generic <K>addEventListener method. The letter K is a placeholder representing the type of event name (such as 'blur' or 'input').

public setTextFieldInputListener(listenerProps: TextFieldListenerProps): void {
    if (isOnBlurTextFieldProps(listenerProps)) {
        this.input.addEventListener<'blur'>(listenerProps.eventName, listenerProps.callback.bind(this));
    } else if (isOnInputTextFieldProps(listenerProps)) {
        this.input.addEventListener<'input'>(listenerProps.eventName, listenerProps.callback.bind(this));
    }
}

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

What is the best way to conceal elements that do not have any subsequent elements with a specific class?

Here is the HTML code I have, and I am looking to use jQuery to hide all lsHeader elements that do not have any subsequent elements with the class 'contact'. <div id="B" class="lsHeader">B</div> <div id="contact_1" class="contac ...

Transferring information between an ASP web form page and an Angular2 application

Currently, I am working on a project that involves dealing with a legacy WebForms system. The system is gradually being updated to Angular 2, but the transition is happening incrementally. In order to effectively integrate information from the legacy sect ...

Getting an input value dynamically in a React variable when there is a change in the input field

I am having an issue with my search text box. I need to extract the value onchange and send a request to an API, but when I try using the normal event.target method, it shows an error. How can I fix this? The problem is that onchange, I need to call a func ...

Manipulating the display style of an element without using jQuery

Could anyone assist me with this issue? I am currently facing a challenge in making the following script functional. It is intended to hide the button after it has been clicked. The script is being called through Ajax and PHP, so I am unable to utilize jQ ...

Securely Saving JWT Tokens from Auth0 Login in Node.js Express

As a novice in the world of Auth0, I am currently working on integrating it into my regular express web application. My main goal is to secure and validate users before they are able to access certain endpoints. From what I have gathered, this can be achie ...

What is the method for accessing appendTo() in the Document Object Model (

I added a duplicated element $canvas to the body in the DOM with this piece of code $('.' + $canvas).clone().appendTo('body'); Now, I want to be able to use it like this $('ul,.map').mousemove(function (e) { $(& ...

Make sure to retain PHP includes/requires when dynamically loading a new page using AJAX

My website has a main page with a header, navbar, footer, and content is loaded using AJAX into a div: <div id="content" class="page-content"></div> I am wondering if it's feasible to load a page dynamically into the content div using AJA ...

Extension: What is the best way to leverage data obtained from an ajax request in order to dynamically modify an already existing element within

I've been trying to find a reliable and comprehensive tutorial for JavaScript (JS) and Ajax, but so far my search has been futile. Unlike Python.org for Python or php.net for PHP, I haven't found a satisfactory resource yet. Any recommendations w ...

The HTML is not rendering as planned

I have 2 files, test.html <!DOCTYPE html> <head> <title>test</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="./test/jquery.min.js"></script> </head> <body> ...

Utilizing Selenium to inject javascript permanently or on every page refresh

In my selenium webdriver test using Python 3, I have implemented a semi-automated process. This means that some routines are automated while other tasks require user interaction with the browser, such as page refreshes or redirects. My challenge is to inj ...

How to add rows at a particular index within another row using ng-repeat

Check out this code snippet: <tr ng-repeat="param in tags[$index].parameters"> <td class="previewParamName">{{param.name}}</td> <td> <div ng-if="is_array(param)"> &l ...

Tips for implementing a generic constant value in a TypeScript function

Is it permissible in TypeScript to have the following code snippet? function getFoo<P = "a"|"b">():string { // P represents a type, not an actual value! return "foo"; } getFoo<"a>">(); // no ...

The AJAX request I'm making is not behaving as I anticipated when returning JSON data

I'm currently working on building an ajax call to compare my database and automatically update a div if any changes are detected. JavaScript is still quite new to me, especially when it comes to dealing with JSON data. I suspect the issue lies in ho ...

Tips for automatically scrolling the Google Maps view in a React application

After implementing the google-map-react package, I have designed a TypeScript MapView component with the following code snippet. export function MapView<I extends Mappable>({ getData }: MapViewProps<I>): JSX.Element { const [mapZoom, setMapZo ...

Changing the background of a Muitextfield input element conceals the label

Struggling to customize the Textfield from the global theme? Can't seem to achieve a colored background for the input only (white) without obscuring the label when it moves inside the input. Desired result : https://i.sstatic.net/us2G7.png Current o ...

Unable to redirect to another page in React after 3 seconds, the function is not functioning as intended

const homeFunction = () => { const [redirect, setRedirect] = useState<boolean>(false); const [redirecting, setRedirecting] = useState<boolean>(false); const userContext = useContext(UserContext); useEffect(() => { const valu ...

What is the best approach for sending a binary image post request to an API using nodejs?

I am receiving the image binary in this manner: axios.get("image-url.jpg") Now, I want to utilize the response to create a new POST request to another server const form = new FormData(); const url = "post-url-here.com"; form.appe ...

Using Jquery ajax, I am interested in storing a single value into a variable for future use in JavaScript

I'm finally able to retrieve a JSON Get request, but I'm struggling with utilizing the information effectively. The array contains 9 items, but I only need one specific value - the id. I want to extract this id and save it in a variable for futur ...

What is the best way to organize divs in a grid layout that adapts to different screen sizes, similar to the style

Is there a way to align multiple elements of varying heights against the top of a container, similar to what is seen on Wolfram's homepage? I noticed that they used a lot of JavaScript and absolute positioning in their code, but I'm wondering if ...

What can cause the reactive value to fail to update in a Vue template?

In my application, I encountered a strange issue where a h3 tag containing a title bound to a reactive data property from a Firestore database would sometimes not display properly after a page reload. Oddly enough, when accessing the page through client-si ...