Home > front end >  Type 'HTMLDivElement | null' is not assignable to type 'HTMLDivElement'
Type 'HTMLDivElement | null' is not assignable to type 'HTMLDivElement'

Time:06-28

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');
  }
};

CodePudding user response:

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');
  • Related