JavaScript
x
6
1
function copy(){
2
var Url=document.getElementById("Id");
3
Url.select(); //error
4
document.execCommand("Copy"); // browser copy
5
}
6
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:
JavaScript
1
3
1
var Url = document.getElementById("Id") as HTMLInputElement;
2
Url.select(); // OK
3
Reason
getElementById
can return any HTMLElement
s. In your case you know its an input element so you can tell TypeScript that by using a type assertion 🌹.