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

2
  • try using var or let instead of const Commented Aug 24, 2017 at 9:19
  • Possible duplicate of querySelector in Typescript Commented Aug 24, 2017 at 9:37

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.