![](/img/trans.png)
[英]document.getElementById(s).document.getElementsByClassName error in typescript
[英]What's Typescript's issue with document.getElementbyID?
请有人选择一个更好的标题,因为坦率地说我不知道该标题的标题。
我想做的是将Textarea的内容作为字符串获取(供NW.js文件功能使用,因为我正在编写在平面文件上做事的应用程序),并且正在使用以下代码来做到这一点:
let file = document.getElementById("txt").value;
在被编译为JS之后就可以正常工作了。 但是,TypeScript编译器抱怨值部分:
Property 'value' does not exist on type 'HTMLElement'
我究竟做错了什么?
TypeScript的存在理由是将静态类型应用于类似JavaScript的代码。 document.getElementById
返回没有value
HTMLElement
(毕竟,它可以是任何种类的HTML元素),因此TypeScript警告您使用的是HTMLElement
没有的属性。 TypeScript不能知道您获取的特定元素是HTMLInputElement
(具有value
),除非您通过强制转换(从技术上讲,是类型断言 )告诉它:
let file = (document.getElementById("txt") as HTMLInputElement).value;
// or
let file = (<HTMLInputElement>document.getElementById("txt")).value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.