typescript “HTMLElement”类型的值上不存在属性“value”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12989741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 00:54:30  来源:igfitidea点击:

The property 'value' does not exist on value of type 'HTMLElement'

typescript

提问by Bjarke Freund-Hansen

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.

我正在玩打字稿并尝试创建一个脚本,该脚本将在输入框中输入文本时更新 p 元素。

The html looks as following:

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>

And the greeter.tsfile:

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);
}

When I compile with tscI get the following "error":

当我编译时tsc出现以下“错误”:

/home/bjarkef/sandbox/greeter.ts(8,53): The property 'value' does not exist on value of type 'HTMLElement'

/home/bjarkef/sandbox/greeter.ts(8,53): The property 'value' does not exist on value of type 'HTMLElement'

However the compiler does output a javascript file, which works just fine in chrome.

然而,编译器确实输出了一个 javascript 文件,它在 chrome 中工作得很好。

How come I get this error? And how can I fix it?

我怎么会收到这个错误?我该如何解决?

Also, where can I look up which properties are valid on a 'HTMLElement'according to typescript?

另外,'HTMLElement'根据打字稿,我可以在哪里查找哪些属性在 a 上有效?

Please note I am very new to javascript and typescript, so I might be missing something obvious. :)

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

回答by Bjarke Freund-Hansen

Based on Tomasz Nurkiewiczs answer, the "problem" is that typescript is typesafe. :) So the document.getElementById()returns the type HTMLElementwhich does not contain a valueproperty. The subtype HTMLInputElementdoes however contain the valueproperty.

根据 Tomasz Nurkiewiczs 的回答,“问题”是打字稿是类型安全的。:) 所以document.getElementById()返回HTMLElement不包含value属性的类型。HTMLInputElement然而,子类型确实包含该value属性。

So a solution is to cast the result of getElementById()to HTMLInputElementlike this:

因此,一个解决方案是投的结果getElementById(),以HTMLInputElement这样的:

var inputValue = (<HTMLInputElement>document.getElementById(elementId)).value;

<>is the casting operator in typescript. See the question TypeScript: casting HTMLElement.

<>是打字稿中的转换运算符。请参阅问题TypeScript:casting HTMLElement

The resulting javascript from the line above looks like this:

上一行的结果 javascript 如下所示:

inputValue = (document.getElementById(elementId)).value;

i.e. containing no type information.

即不包含类型信息。

回答by Michael

If you are using react you can use the asoperator.

如果您使用的是 react,则可以使用as运算符。

let inputValue = (document.getElementById(elementId) as HTMLInputElement).value;

回答by woodysan

Try casting the element you want to update to HTMLInputElement. As stated in the other answers you need to hint to the compiler that this is a specific type of HTMLElement:

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

var inputElement = <HTMLInputElement>document.getElementById('greet');
inputElement.value = greeter(inputValue);

回答by Leo

Updated example:

更新示例:

const inputElement: HTMLInputElement = document.getElementById('greet') as HTMLInputElement
const inputValue: string = inputElement.value

Documentation from Typescriptlang:

Typescriptlang 的文档:

TypeScript - Basic Types - Type assertions

TypeScript - 基本类型 - 类型断言

回答by Tomasz Nurkiewicz

The problem is here:

问题在这里:

document.getElementById(elementId).value

You know that HTMLElementreturned from getElementById()is actually an instance of HTMLInputElementinheriting from it because you are passing an ID of input element. Similarly in statically typed Java this won't compile:

您知道HTMLElement返回getElementById()的实际上是HTMLInputElement从它继承的实例,因为您传递的是输入元素的 ID。同样,在静态类型的 Java 中,这不会编译:

public Object foo() {
  return 42;
}

foo().signum();

signum()is a method of Integer, but the compiler only knows the static type of foo(), which is Object. And Objectdoesn't have a signum()method.

signum()是 的方法Integer,但编译器只知道 的静态类型foo(),即Object. 并且Object没有signum()方法。

But the compiler can't know that, it can only base on static types, not dynamic behaviour of your code. And as far as the compiler knows, the type of document.getElementById(elementId)expression does not have valueproperty. Only input elements have value.

但是编译器不知道,它只能基于静态类型,而不是代码的动态行为。而且据编译器所知,document.getElementById(elementId)表达式的类型没有value属性。只有输入元素才有价值。

For a reference check HTMLElementand HTMLInputElementin MDN. I guess Typescript is more or less consistent with these.

用于参考检查HTMLElementHTMLInputElementMDN。我猜 Typescript 或多或少与这些一致。

回答by inDream

A quick fix for this is use [ ] to select the attribute.

对此的快速解决方法是使用 [ ] 选择属性。

function greet(elementId) {
    var inputValue = document.getElementById(elementId)["value"];
    if(inputValue.trim() == "") {
        inputValue = "World";
    }
    document.getElementById("greet").innerText = greeter(inputValue);
}

I just try few methods and find out this solution,
I don't know what's the problem behind your original script.

我只是尝试了几种方法并找到了这个解决方案,
我不知道您原始脚本背后的问题是什么。

For reference you may refer to Tomasz Nurkiewicz's post.

作为参考,您可以参考 Tomasz Nurkiewicz 的帖子。

回答by KidKode

Also for anyone using properties such as Props or Refs without your "DocgetId's" then you can:

同样对于使用 Props 或 Refs 等属性而没有“DocgetId”的任何人,您可以:

("" as HTMLInputElement).value;

Where the inverted quotes is your props value so an example would be like so:

反引号是你的道具值,所以一个例子是这样的:

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

回答by Rohit Grover

If you are using angular you can use -

如果您使用的是角度,则可以使用 -

const element = document.getElementById('elemId') as HTMLInputElement;

回答by Juan Pablo

This work for me:

这对我有用:

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

回答by Alok Adhao

Problem:

问题:

error Property 'text' does not exist on type 'HTMLElement'

类型“HTMLElement”上不存在错误属性“文本”

Solution: in typeScript we need to cast document.getElementById()which returns type HTMLElementin < HTMLScriptElement >

解决方案:在打字稿我们需要铸造document.getElementById()返回类型HTMLElement< HTMLScriptElement >

So we can do it by by following way to resolve the error as expected by typescript.js

所以我们可以通过以下方式解决typescript.js预期的错误

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

It worked for me.. hope it works for you as well.

它对我有用..希望它也适用于你。