Skip to content
Advertisement

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

Advertisement

Answer

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 🌹.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement