简体   繁体   English

错误:类型 HTMLElement 上不存在属性“选择”

[英]error:Property 'select' does not exist on type HTMLElement

没有错误本地演示

vscode 报错

 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

Reason原因

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.

相关问题 错误TS2339:类型“ HTMLElement”上不存在属性“ imageID” - error TS2339: Property 'imageID' does not exist on type 'HTMLElement' useRef Typescript 错误:“HTMLElement”类型上不存在属性“current” - useRef Typescript error: Property 'current' does not exist on type 'HTMLElement' 打字稿错误:&#39;HTMLElement&#39;类型中不存在属性&#39;append&#39; - Typescript Error: Property 'append' does not exist on type 'HTMLElement' 错误TS2339:类型“ HTMLElement”上不存在属性“名称” - error TS2339: Property 'name' does not exist on type 'HTMLElement' 类型“JQuery”上不存在属性“slick”<HTMLElement> &#39; - Property 'slick' does not exist on type 'JQuery<HTMLElement>' 类型“ HTMLElement”上不存在属性“ length” - Property 'length' does not exist on type 'HTMLElement' “HTMLElement”类型上不存在属性“r” - Property 'r' does not exist on type 'HTMLElement' 类型“JQuery”上不存在属性“模态”<HTMLElement> &#39; - Property 'modal' does not exist on type 'JQuery<HTMLElement>' 类型“JQuery”上不存在属性“掩码”<HTMLElement> - Property 'mask' does not exist on type 'JQuery<HTMLElement> 类型“ HTMLElement”上不存在属性“ pseudoStyle” - Property 'pseudoStyle' does not exist on type 'HTMLElement'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM