typescriptsharepoint-onlinespfx

I am getting Type Null is not assignable to to type Element


private _renderListOfLists(items : ISharePointList[]):void {
    let html : string = '';

    items.forEach((item:ISharePointList) => {
      html += `
      <ul class = "">
        <li class = ""><span class="ms-font-1">${item.ListTitle}</span></li>
        <li class = ""><span class="ms-font-1">${item.ListID}</span></li> 
      </ul>
      `;
      }
    );

    const listsPlaceholder : Element = this.domElement.querySelector('#SPListPlaceHolder');
    listsPlaceholder.innerHTML = html;

}

I am getting the below error message:

Type 'Element | null' is not assignable to type 'Element'. Type 'null' is not assignable to type 'Element'.ts(2322) const listsPlaceholder: Element

Can someone please help with this?

I am not sure why I am getting the syntax error message


Solution

  • querySelector may return null if no element is found.

    If you're certain the element is present, you may assert the type with as:

    const listsPlaceholder = this.domElement.querySelector('#SPListPlaceHolder') as Element;
    

    Otherwise, you'll have to check before TypeScript lets you use the value as an Element.

    const listsPlaceholder = this.domElement.querySelector('#SPListPlaceHolder');
    if (listsPlaceholder === null) throw new Error('placeholder element not found')
    listsPlaceholder.innerHTML = html;