1

I am getting an error while converting the following code to typescript.

const element = document.querySelector('#launcher');
if (element && element.style && element.style.display) {
    element.style.display = '';
}

error TS2339: Property 'style' does not exist on type 'Element'.

and when I assign required values for same as like below

const element: { style: any } = document.querySelector('#launcher');

then the error is on the element and that is

error TS2322: Type 'Element | null' is not assignable to type '{ style: any; }'. Type 'null' is not assignable to type '{ style: any; }'.

YakovL
  • 7,557
  • 12
  • 62
  • 102
Suhas Gavad
  • 1,199
  • 1
  • 8
  • 12

2 Answers2

5

document.querySelector returns instance of Element. And there is not much declared in the typings for it. In order to fix the error - cast it to more specific type, for example:

const element = document.querySelector('#launcher') as HTMLInputElement;
if (element && element.style && element.style.display)
{
    element.style.display = '';
}

Basically everything that inherits from HTMLElement will do the job.

Amid
  • 21,508
  • 5
  • 57
  • 54
1

I would recommend giving specific types while declaring variables.

For eg: in your case the querySelector returns value of type 'Element|null' So, you can define your element variable like this

const element: Element = document.querySelector('#launcher');

Hope this helps.

Nikit Prabhu
  • 131
  • 4