我玩周围的typescript,并试图创建一个脚本,将更新一个p元素作为文本输入在一个输入框。

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>

还有迎宾员。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编译时,我得到以下“错误”:

/home/bjarkef/sandbox/ setter .ts(8,53):属性“value”在类型为“HTMLElement”的值上不存在

然而,编译器会输出一个javascript文件,这在chrome中工作得很好。

我怎么得到这个错误?我该怎么解决呢?

此外,我可以在哪里查找哪些属性是有效的“HTMLElement”根据typescript?

请注意,我对javascript和typescript很陌生,所以我可能会遗漏一些明显的东西。:)


当前回答

问题:

属性“text”在类型“HTMLElement”上不存在

解决方案:在typeScript中,我们需要强制转换document.getElementById(),它返回< HTMLScriptElement >中的HTMLElement类型

因此,我们可以按照typescript.js所期望的方法来解决错误

Code: var content: string = ( < HTMLScriptElement > document.getElementById(contentId)).text;

这对我很管用。希望这对你也有用。

其他回答

我一直有一个类似的问题(TS警告在JS文件:“属性X不存在的类型X”:它是可能写更干净的JavaScript?)

虽然标记帮助删除了typescript文件中的警告,但在编译后,JavaScript文件中仍然会出现警告。

那么,我如何编写代码,这是干净的,并允许我操作。value ?

这花了我不少时间,但我用另一种方法找到了解决方法:

HTML代码:

<form id="my-form" 
   action="index.html"
   method="get"
   onsubmit="return showValue();">
    <input type="text" name="username">
    <input type="text" name="full-name">
    <input type="password" name="password">
    <button type="button" onclick="showValue();">Show value</button>
</form>

Javascript代码:

function showValue() {
    const myForm = document.forms.my-form;
    console.log(myForm?.username.value);
    return 1;
}

document.forms.x有一个属性“value”,它可以删除typescript文件和生成的JavaScript中的警告。

尝试将你想要更新的元素转换为HTMLInputElement。正如在其他答案中所述,你需要提示编译器,这是一个特定类型的HTMLElement:

var inputElement = <HTMLInputElement>document.getElementById('greet');
inputElement.value = greeter(inputValue);
  const handleMyEvent = (event : React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    
    const input = (event.target as HTMLInputElement).value;
    console.log('handleMyEvent input -> ', input)

  }

同样对于任何人使用属性,如Props或Refs没有你的“DocgetId’s”,那么你可以:

("" as HTMLInputElement).value;

这里的倒引号是你的props值,所以一个例子是这样的:

var val = (this.refs.newText as HTMLInputElement).value;
alert("Saving this:" + val);

这对我来说很有用:

let inputValue = (swal.getPopup().querySelector('#inputValue ')as HTMLInputElement).value