Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Type 'HTMLDivElement | null' is not assignable to type 'HTMLDivElement'

I’m working on this scroll function to lock the position while scrolling up or down
and I have encountered below error

Type 'HTMLDivElement | null' is not assignable to type 'HTMLDivElement'.
Type 'null' is not assignable to type 'HTMLDivElement'.ts(2322)

Could anyone help me resolving this error?

scroll = (): void => {
  if (this.isLargerScreenMedia()) {
    this.applyLargeMediaStyles();
  } else {
    const scrollPos: number = document.documentElement.scrollTop;
    const totalCon: HTMLDivElement =
      this.tripTotalContainer.querySelector('.trip-total-module');
    if (totalCon) {
      if (scrollPos > this.lastScrollPos) {
        //scroll down
        totalCon.style.bottom = '0px';
      } else {
        //scroll up
        totalCon.style.bottom = '27px';
      }
    }
    this.lastScrollPos = scrollPos < 0 ? 0 : scrollPos;
    this.tripTotalContainer.classList.add('sticky-bottom');
  }
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The querySelector method has a return type of Element | null – if no matching element(s) are found, null will be returned.

So, this line is causing the error you’re seeing, since you’re saying that totalCon is of type HTMLDivElement (without accounting for null):

const totalCon: HTMLDivElement = this.tripTotalContainer.querySelector('.trip-total-module');

It looks like the rest of your code already checks if totalCon is "falsy", so you could resolve this by just removing the explicit type declaration:

const totalCon = this.tripTotalContainer.querySelector('.trip-total-module');

Alternatively, you could make the explicit type declaration match the return type of querySelector:

const totalCon: HTMLDivElement | null = this.tripTotalContainer.querySelector('.trip-total-module');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading