TypeScript中的EventTarget类型中不存在属性“value” [英] Property 'value' does not exist on type EventTarget in TypeScript
问题描述
所以下面的代码是在Angular 4中,我无法弄清楚为什么它没有按预期方式工作。
So the following code is in Angular 4 and I can't figure out why it doesn't work the way as expected.
这是我的一小部分代码handler:
Here is a snippet of my handler:
onUpdatingServerName(event: Event) {
console.log(event);
this.newserverName = event.target.value; //this wont work
}
HTML元素:
<input type="text" class="form-control" (input)="onUpdatingServerName($event)">
该代码给出了错误:
'EventTarget'类型中不存在属性'值'。
Property 'value' does not exist on type 'EventTarget'.
但是可以看出在 console.log
中该值确实存在于 event.target
。
But as it can be seen in the console.log
that value does exist on the event.target
.
推荐答案
event.target
这是一个 HTMLElement
哪个是所有HTML元素的父级,但不保证具有属性值
。 TypeScript检测到此并抛出错误。将 event.target
转换为相应的HTML元素,以确保它是 HTMLInputElement
哪个值
属性:
event.target
here is an HTMLElement
which is the parent of all HTML elements, but isn't guaranteed to have the property value
. TypeScript detects this and throws the error. Cast event.target
to the appropriate HTML element to ensure it is HTMLInputElement
which does have a value
property:
(<HTMLInputElement>event.target).value
每文档:
输入
$ event
以上示例投射
$事件
作为任何
类型。这样可以降低代码的成本。没有类型信息可以揭示事件对象的属性并防止出现愚蠢的错误。
Type the
$event
The example above casts the
$event
as anany
type. That simplifies the code at a cost. There is no type information that could reveal properties of the event object and prevent silly mistakes.
[...]
$ event
现在是一个特定的 KeyboardEvent
。 并非所有元素都具有值
属性,因此它会将 target
强制转换为输入元素。
The $event
is now a specific KeyboardEvent
. Not all elements have a value
property so it casts target
to an input element.
(强调我的)
这篇关于TypeScript中的EventTarget类型中不存在属性“value”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!