1
votes

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

2
try using var or let instead of const - Sibiraj
Possible duplicate of querySelector in Typescript - Sibiraj

2 Answers

5
votes

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.

1
votes

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.