Hi, I'm getting this error
ts(2339) Property 'classList' does not exist on type 'Node & ParentNode'.
on something that does have a classList. There's a workaround at the end.
TypeScript Version: 3.7.x-dev.201xxxxx
Search Terms:
Code
// TS says the type of elem is Element
const elem = document.querySelector( '#parent > .child' );
// This is ok
elem.classList.add( 'a-class' );
// TS says the type of elem.parentNode is Node & ParentNode
// This fails
elem.parentNode.classList.add( 'another-class' );
Expected behavior:
To actually pass type checking.
Actual behavior:
Type checking fails with message
TS2339: Property 'classList' does not exist on type 'Node & ParentNode'.
Similar issues
Saw around the web other similar issues like _Property 'querySelector' does not exist on type 'Node'_
Workaround
I had to do this to pass type checking.
(<Element>elem.parentNode).classList.add( 'another-class' );
Just guessing, but could this be because the parentNode of an 'html' element is a Document, which doesn't have a classList? So the general statement elem.parentNode.classList.add could thrown, depending on what 'elem' refers to.
In this case, child was an <a>, parent an <li>. Both have classList.
Sure, but tsc can't statically know that. It would have to have deep understanding of the CSS selector '#parent > .child'.
This issue has been marked as 'Question' and has seen no recent activity. It has been automatically closed for house-keeping purposes. If you're still waiting on a response, questions are usually better suited to stackoverflow.
Most helpful comment
Just guessing, but could this be because the parentNode of an 'html' element is a Document, which doesn't have a classList? So the general statement
elem.parentNode.classList.addcould thrown, depending on what 'elem' refers to.