Skip to content

How to define data type for queryselector in typescript

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.


public getMatch:any;
public readyCont:any;

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



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");