[英]error:Property 'select' does not exist on type HTMLElement
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.我认为 select() 是有效的(链接),因为我在演示中使用它时可以正确复制。 my ts version is 2.8.1我的 ts 版本是 2.8.1
You need to add a type assertion :您需要添加一个类型断言:
var Url = document.getElementById("Id") as HTMLInputElement;
Url.select(); // OK
getElementById
can return any HTMLElement
s. getElementById
可以返回任何HTMLElement
。 In your case you know its an input element so you can tell TypeScript that by using a type assertion 🌹.在您的情况下,您知道它是一个输入元素,因此您可以使用类型断言 🌹 告诉 TypeScript。
select
method is defined for HTMLInputElement s. select
方法是为HTMLInputElement定义的。 The following will get rid of the TypeScript error.以下将摆脱 TypeScript 错误。
let Url: HTMLInputElement = document.getElementById("Id") as HTMLInputElement;
Url.select();
document.execCommand("Copy");
You need to specify the correct type of the element, because React thinks it's just an HTMLElement instead of HTMLInputElement.你需要指定元素的正确类型,因为 React 认为它只是一个 HTMLElement 而不是 HTMLInputElement。
So, change to it!所以,改变它!
var Url=document.getElementById("Id") as HTMLInputElement; var Url=document.getElementById("Id") as HTMLInputElement;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.