“HTMLElement"类型的值上不存在属性“value" [英] The property 'value' does not exist on value of type 'HTMLElement'
问题描述
我正在玩打字稿,并试图创建一个脚本,该脚本将在输入框中输入文本时更新 p 元素.
I am playing around with typescript and am trying to create a script that will update a p-element as text is inputted in a input box.
html 如下所示:
<html>
<head>
</head>
<body>
<p id="greet"></p>
<form>
<input id="name" type="text" name="name" value="" onkeyup="greet('name')" />
</form>
</body>
<script src="greeter.js"></script>
</html>
还有 greeter.ts
文件:
function greeter(person)
{
return "Hello, " + person;
}
function greet(elementId)
{
var inputValue = document.getElementById(elementId).value;
if (inputValue.trim() == "")
inputValue = "World";
document.getElementById("greet").innerText = greeter(inputValue);
}
当我使用 tsc
进行编译时,出现以下错误":
When I compile with tsc
I get the following "error":
/home/bjarkef/sandbox/greeter.ts(8,53): 'HTMLElement' 类型的值不存在属性 'value'
然而,编译器确实输出了一个 javascript 文件,它在 chrome 中工作得很好.
However the compiler does output a javascript file, which works just fine in chrome.
我怎么会收到这个错误?我该如何解决?
此外,根据打字稿,我可以在哪里查找 'HTMLElement'
上哪些属性有效?
Also, where can I look up which properties are valid on a 'HTMLElement'
according to typescript?
请注意,我对 javascript 和 typescript 非常陌生,所以我可能会遗漏一些明显的东西.:)
Please note I am very new to javascript and typescript, so I might be missing something obvious. :)
推荐答案
根据 Tomasz Nurkiewicz 的回答,问题"是 typescript 是类型安全的.:) 所以 document.getElementById()
返回不包含 value
属性的 HTMLElement
类型.但是子类型 HTMLInputElement
确实包含 value
属性.
Based on Tomasz Nurkiewiczs answer, the "problem" is that typescript is typesafe. :) So the document.getElementById()
returns the type HTMLElement
which does not contain a value
property. The subtype HTMLInputElement
does however contain the value
property.
所以一个解决方案是将 getElementById()
的结果转换为 HTMLInputElement
像这样:
So a solution is to cast the result of getElementById()
to HTMLInputElement
like this:
var inputValue = (<HTMLInputElement>document.getElementById(elementId)).value;
<>
是打字稿中的转换运算符.请参阅问题 TypeScript:转换 HTMLElement.
<>
is the casting operator in typescript. See the question TypeScript: casting HTMLElement.
上一行生成的 javascript 如下所示:
The resulting javascript from the line above looks like this:
inputValue = (document.getElementById(elementId)).value;
即不包含类型信息.
这篇关于“HTMLElement"类型的值上不存在属性“value"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!