简体   繁体   中英

“TS2339: Property … does not exist on type …”, on input field

I have an input field which, when a user clicks a certain button, needs to be focused and have its text value selected entirely (that way when users type, they replace the entire value).

Here's the input field's markup:

<input type="text" id="descriptionField" class="form-control">

...and the function responsible for focus/select:

public copy(): void {
    document.getElementById("descriptionField").focus();
    document.getElementById("descriptionField").select();
}

.focus() works fine, but .select() throws an error:

TS2339: Property 'select' does not exist on type 'HTMLElement'.

I've tried looking for solutions but most of them rely on jQuery. Is there any way to solve this with native implementation, or with TypeScript?

You can "type-cast" the HTMLElement to a type which has the select method :

(document.getElementById("descriptionField") as HTMLInputElement).select();

or:

(<HTMLInputElement>document.getElementById("descriptionField")).select();

This basically tells the compiler "don't worry, I know what type is expected here." , and is called Type Assertions in TypeScript.

It does not affect the runtime, just reassures the compiler so it won't have anything to complain about.

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