Home > Software engineering >  Argument of type 'NodeListOf<Element>' is not assignable to parameter of type '
Argument of type 'NodeListOf<Element>' is not assignable to parameter of type '

Time:04-15

Jumping in the deep end with Typescript and running into the following error:

Error

Argument of type 'NodeListOf<Element>' is not assignable to parameter of type 'Node'.

Script.js

let name;
const targetNode = document.querySelectorAll('[data="record"]');
const config = { attributes: true };

const callback = () => {
    const recordNameString = targetNode[1].textContent;
    const nameArray = recordNameString.split(' ');
    name = nameArray[0];

    chrome.storage.local.set({ name });

    console.log(name);
};

const observer = new MutationObserver(callback);

// Error kicks in here
observer.observe(targetNode, config);

Why is this occuring and how can I resolve?

CodePudding user response:

At this line:

observer.observe(targetNode, config)

targetNode is of type NodeListOf<Element>, which is not the same as type Node: it's a list of Elements. The method observe expects a first argument of type Node.

The type Element extends type Node, though, so you can do this:

targetNode.forEach(node => observer.observe(node, config));

if you're wanting all of the elements in that list to be observed.

TS Playground

  • Related