Reputation: 4756
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?
Upvotes: 4
Views: 3366
Reputation: 16263
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.
Upvotes: 5