Typescript encountering issues with addEventListener

const [status, setStatus] = useState<string>("pending");

const updateStatus = (newStatus: string) => {
  setStatus(newStatus);
};

useEffect(() => {
  window.addEventListener("updateProtocol", updateStatus);
  return () => window.removeEventListener("updateProtocol", updateStatus);
}, []);

window.addEventListener("updateProtocol", updateStatus) is causing an error message:

Type '(newStatus: string) => void' is not compatible with type 'EventListener'.

Answer №1

When using the addEventListener method, make sure to pass an Event object instead of a string.

Ensure that you are using the correct types:

const [locked, setLocked] = useState<string>("pending");

const unlockHandler = (e: {target:{name:string}}) => {
  setLocked(e.target.name);
};

useEffect(() => {
  window.addEventListener("unlockProtocol", unlockHandler);
  return () => window.removeEventListener("unlockProtocol", unlockHandler);
}, []);

Answer №2

Answer in Brief

The type definition for EventListener is as follows:

interface EventListener {
    (evt: Event): void;
}

It requires an Event as the first argument, not a string. Therefore, your event handler should be able to accept an Event and extract necessary information from it to set the locked state.

In-depth Explanation

Lets troubleshoot the issue step by step.

The signature for window.addEventListener is defined as:

interface Window extends EventTarget {
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
}

You have passed the string value unlockProtocol as the first argument. Since this does not match any key on WindowEventMap, it defaults to the second overload where the listener should match

EventListenerOrEventListenerObject
.

Your handler has been inferred as (e: string) => void, which needs to comply with

EventListenerOrEventListenerObject
whose type is either EventListener or EventListenerObject.

Hence, the error arises because the function expects an Event as the first argument according to EventListener's signature. Modify your event handler to handle an Event and use the necessary data to manage your application's locked state.

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 field '_id' is not present in the type Pick

I'm working on a project using Next.js and attempting to query MongoDB with TypeScript and mongoose, but I keep encountering a type error. types.d.ts type dbPost = { _id: string user: { uid: string name: string avatar: string } po ...

Detecting changes in Angular when the @Input() value remains the same

I have created an Angular Custom scroll directive that utilizes an @Input() to pass an HTML element as a parameter, allowing the scrollbar to move to that specific element. However, I've encountered an issue where if I pass the same HTML Element mult ...

Overriding the 'first' attribute in PrimeNG's lazy table when implementing filtering

I encountered an issue while attempting to set up a primeNG table using query parameters. For example, when accessing , the data displayed should pertain to "Joe" and start at the 20th entry. To handle the large volume of data my backend can provide, lazy ...

picker elementClass()

I encountered an issue while using the datepicker from Material UI. The datepicker has a method called dateClass: dateClass() { return (date: Date): MatCalendarCellCssClasses => { const unvailableArray = this.shareDate.unavailableDates; ...

Incorporate Canvg version 4 into a TypeScript project

I am currently facing an issue with an older TypeScript project that has the following tsconfig setup: { "compilerOptions": { "baseUrl": "./src", "outDir": "build/dist", "module": &q ...

Every time I attempt to destructure the state object in react typescript, I encounter the error message stating 'Object is possibly undefined'

Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'. When I try using optional chaining, a different error pops up saying const newUser: NewUser | undefined Argument o ...

Are there any other methods besides @ViewChild to access template elements by template ID in Angular v4.3.3?

In the past, using @ViewChild('#templateId') was an accepted method for obtaining an Element Reference. @ViewChild('#templateId') elementName: ElementRef; However, it appears that this is no longer a viable approach as @ViewChild now ...

Choose a date range from the date picker

I am currently attempting to combine two dates using a rangepicker. Below is the command used to select the date: Cypress.Commands.add('setDatePickerDate', (selector, date) => { const monthsShort = [ 'janv.', 'févr.& ...

Whenever I attempt to render a component passed as a prop, I encounter error TS2604

I am attempting to pass a component as a prop to another component in order to wrap the content of a material ui modal This is my attempt so far: import React, { Component } from 'react'; import withWidth, { isWidthDown } from '@material-u ...

Unable to bring in a personalized npm package using its package title

Currently, I am loosely following a tutorial on creating an angular npm package named customlib. This package is intended for managing dependencies across my projects without the need to make them public on npm. The tutorial can be found here. However, I ...

Remove httpOnly cookies in Express

Can browser cookies with the attribute HttpOnly:true be deleted? Here is a snippet of my login endpoint: async login(@Ip() ipAddress, @Request() req, @Res() res: Response) { const auth = await this.basicAuthService.login(req.user, ipAddress); ...

How to configure dynamic columns in material-table using React and TypeScript

My task involves handling a table with a variable number of columns that are generated dynamically based on the data received. To manage these columns, I have designed an interface that defines various properties for each column, such as whether it can be ...

Executing Functions from Imported Modules in Typescript

Is there a way to dynamically call a method from my imported functions without hard-coding each function name in a switch statement? I'm looking for a solution like the following code: import * as mathFn from './formula/math'; export functi ...

Custom React components are not designed to handle multiple onClick events simultaneously

One of my custom button components looks like this: export const Button = ({ children, onClick, className, ...props }: IButton) { const [selected, setSelected] = React.useState('primary') const handleSelected = () => { setSele ...

React is up and running smoothly on my local machine, but unfortunately encountering issues on Vercel

I have encountered an issue while trying to deploy my website on Vercel. Despite the build logs showing a successful compilation, I am receiving a "failed to compile" error: [16:43:24.951] Running build in Washington, D.C., USA (East) – iad1 [16:43:25.05 ...

How can you partially update an entity in TypeORM using a query runner?

Updating a user's name partially is simple with the repository save method: await this.repository.save({ id: 1, name: 'john' }); However, when attempting to do the same using queryrunner, all fields must exist which throws an error stating ...

What is the best way to send an enum from a parent component to a child component in

I'm trying to send an enum from a parent component to a child component. This is the enum in question: export enum Status { A = 'A', B = 'B', C = 'C' } Here's the child component code snippet: @Component({ ...

Challenges encountered when retrieving parameters from union types in TypeScript

Why can't I access attributes in union types like this? export interface ICondition { field: string operator: string value: string } export interface IConditionGroup { conditions: ICondition[] group_operator: string } function foo(item: I ...

Avatar image is not displaying correctly when I try to use it with the Mui selectTag component

I am encountering an issue while using avatar in MUI to display images in tagSelect. <FormControl sx={{ width: "27.5rem" }}> <InputLabel id="demo-multiple-checkbox-label">Tag</InputLabel> <Select lab ...

Can you explain how this promise functions within the context of the mutation observer, even without an argument?

Recently, I came across a mutation observer in some TypeScript code that has left me puzzled. This particular implementation of a promise within the mutation observer seems unconventional to me: const observer = new MutationObserver((mutations: MutationR ...