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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49911541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:21:59  来源:igfitidea点击:

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

javascripttypescriptvisual-studio-code

提问by John

no error local demo

没有错误本地演示

vscode complains error

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. my ts version is 2.8.1

如上。我正在尝试创建一个函数来复制浏览器中的文本。但是在打字稿中出现标题错误。我认为 select() 是有效的(链接),因为我在演示中使用它时可以正确复制。我的 ts 版本是 2.8.1

回答by basarat

You need to add a type assertion:

您需要添加一个类型断言

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

Reason

原因

getElementByIdcan return any HTMLElements. In your case you know its an inputelement so you can tell TypeScript that by using a type assertion .

getElementById可以返回任何HTMLElements。在您的情况下,您知道它是一个输入元素,因此您可以使用类型断言告诉 TypeScript。

回答by GSSwain

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

select方法是为HTMLInputElement定义的。以下将摆脱 TypeScript 错误。

let Url: HTMLInputElement = document.getElementById("Id") as HTMLInputElement;
Url.select();
document.execCommand("Copy");