Home > Software engineering >  type '...' is not assignable to parameter of type '...' TS 2345
type '...' is not assignable to parameter of type '...' TS 2345

Time:08-29

I'm trying to write this function in my project and I got this error:

:Argument of type '(item: HTMLElement) => void' is not assignable to parameter of type '(value: Element, key: number, parent: NodeListOf<Element>) => void'.
  Types of parameters 'item' and 'value' are incompatible.
    Type 'Element' is missing the following properties from type 'HTMLElement': accessKey, accessKeyLabel, autocapitalize, dir, and 113 more.ts(2345).

this is the function:

document.querySelectorAll(".choose").forEach(function (item: HTMLElement) {
  item.addEventListener("click", function (e) {
    e.preventDefault();
    (document.querySelector(".card__timer") as HTMLElement).style.display = "block";
    document
      .querySelectorAll(".card__block:not(.card__timer)")
      .forEach(function (el: HTMLElement) {
        el.style.display = "none";
      });
    startTimer();
  });
});

CodePudding user response:

document.querySelectorAll returns a NodeList of Elements, but your forEach-callbacks process HTMLElements, which are more specific.

CodePudding user response:

Just remove the type HTMLElement from both item and el arguments and it should work. Do it like the following:

document.querySelectorAll(".choose").forEach(function (item) {
  item.addEventListener("click", function (e) {
    e.preventDefault();
    (document.querySelector(".card__timer") as HTMLElement).style.display = "block";
    document
      .querySelectorAll(".card__block:not(.card__timer)")
      .forEach(function (el) {
        (el as HTMLElement).style.display = "none";
      });
    startTimer();
  });
});
  • Related