TypeScript 中的 EventTarget 类型不存在属性“值" [英] 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.
这是我的处理程序的片段:
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"上不存在属性value".
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 元素的父元素,但不是't 保证有属性value
.TypeScript 检测到这一点并抛出错误.将 event.target
转换为适当的 HTML 元素,以确保它是具有 value
属性的 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
转换为 any
类型.这需要付出代价来简化代码.没有类型信息可以揭示事件对象的属性并防止愚蠢的错误.
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
.并非所有元素都有 value
属性,因此它会将 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 类型不存在属性“值"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!