Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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?

like image 920
Nicolas Avatar asked Nov 07 '25 08:11

Nicolas


1 Answers

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.

like image 137
Eliran Malka Avatar answered Nov 08 '25 22:11

Eliran Malka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!