1

I am trying to define the data type for query selector in typescript, But I do not know how to define it. I have defined any. But any is not a good way. So, How to define the data type for query selector.

test.ts:

public getMatch:any;
public readyCont:any;

this.getMatch = document.querySelector("#exampleId");
this.readyCont = this.getMatch.shadowRoot.querySelector("#matchId");
3
  • VScode tells me getMatch is of type Element when I hover it. You can write public getMatch:Element; Commented Dec 28, 2021 at 14:58
  • check this out: stackoverflow.com/questions/43032004/queryselector-in- typescript , you can cast it as HTMLInputElement Commented Dec 28, 2021 at 15:00
  • According to .querySelector() MDN docs, method returns the first Element within the document that matches the specified selector, or group of selectors. So you can declare getMatch type: public getMatch: Element Commented Dec 28, 2021 at 15:03

2 Answers 2

3

querySelector is a generic function. If you don't pass a type into it then it returns an Element. Assuming you are querying an HTML document and not anything with SVG elements in it then it is safe to assume that it returns an HTMLElement. You can pass this type into the function so you can do:

public getMatch:HTMLElement
this.getMatch = document.querySelector<HTMLElement>("#exampleId");

However if you know the type of element you are querying then you can be a bit more specific, eg

public getMatch:HTMLInputElement
this.getMatch = document.querySelector<HTMLInputElement>("#exampleId");
Sign up to request clarification or add additional context in comments.

Comments

1

querySelector() returns an HTMLElement or null if he can't find it.

public getMatch: HTMLElement | null;
public readyCont: HTMLElement | null;

this.getMatch = document.querySelector("#exampleId");
this.readyCont = this.getMatch.shadowRoot.querySelector("#matchId");

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.