简体   繁体   中英

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.

test.ts:

public getMatch:any;
public readyCont:any;

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

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

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

querySelector() returns an HTML element. The type of HTML element depends on what you are querying.

In typescript, you can declare it as HTMLElement .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM