错误:HTMLElement类型中不存在属性'select'

Joh*_*ohn 8 javascript typescript visual-studio-code

没有错误本地演示

vscode抱怨错误

 function copy(){
        var Url=document.getElementById("Id");
        Url.select(); //error
        document.execCommand("Copy"); // browser copy
        }
Run Code Online (Sandbox Code Playgroud)

如上.我正在尝试创建一个在浏览器中复制文本的功能.但错误作为标题出现在typescript中.select()是有效的我认为(链接),因为当我在演示中使用它时我可以正确复制.我的ts版本是2.8.1

bas*_*rat 38

您需要添加一个类型断言:

var Url = document.getElementById("Id") as HTMLInputElement;
Url.select(); // OK
Run Code Online (Sandbox Code Playgroud)

原因

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


GSS*_*ain 6

select方法是为HTMLInputElement定义的。以下内容将消除 TypeScript 错误。

let Url: HTMLInputElement = document.getElementById("Id") as HTMLInputElement;
Url.select();
document.execCommand("Copy");
Run Code Online (Sandbox Code Playgroud)