Reputation: 1229
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; }'.
Upvotes: 1
Views: 11152
Reputation: 156
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.
Upvotes: 1
Reputation: 22382
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.
Upvotes: 5