'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看起来如下:
The html looks as following:
<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'类型的值
然而编译器确实输出了一个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和打字稿很新,所以我可能会遗漏一些明显的东西。 :)
Please note I am very new to javascript and typescript, so I might be missing something obvious. :)
推荐答案
根据Tomasz Nurkiewiczs的回答,问题是打字稿是类型安全的。 :)所以 document.getElementById()
返回类型 HTMLElement
,它不包含值
属性。但是,子类型 HTMLInputElement
确实包含值
属性。
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屋!