Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error:Property 'select' does not exist on type HTMLElement

no error local demo

vscode complains error

 function copy(){
        var Url=document.getElementById("Id");
        Url.select(); //error
        document.execCommand("Copy"); // browser copy
        }

as above. I'm trying to make a function to copy text in browser.but the error as title occurred in typescript. the select() is valid I think(link),since I can copy correctly when I use it in a demo. my ts version is 2.8.1

like image 658
John Avatar asked Apr 19 '18 01:04

John


People also ask

What is HTMLInputElement?

The HTMLInputElement interface provides special properties and methods for manipulating the options, layout, and presentation of <input> elements.


2 Answers

You need to add a type assertion:

var Url = document.getElementById("Id") as HTMLInputElement;
Url.select(); // OK

Reason

getElementById can return any HTMLElements. In your case you know its an input element so you can tell TypeScript that by using a type assertion 🌹.

like image 75
basarat Avatar answered Oct 13 '22 08:10

basarat


select method is defined for HTMLInputElements. The following will get rid of the TypeScript error.

let Url: HTMLInputElement = document.getElementById("Id") as HTMLInputElement;
Url.select();
document.execCommand("Copy");
like image 24
GSSwain Avatar answered Oct 13 '22 07:10

GSSwain