HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptangularCritical

Property 'value' does not exist on type EventTarget in TypeScript

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
propertyexisttypescripteventtargetdoesnotvaluetype

Problem

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 element:



The code gives me the error:


Property 'value' does not exist on type 'EventTarget'.

But as it can be seen in the console.log that value does exist on the event.target.

Solution

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:

(event.target as HTMLInputElement).value


Per the documentation:

Type the $event

The example above casts the $event as an any 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.

[...]

The $event is now a specific KeyboardEvent. Not all elements have a value property so it casts target to an input element.

(Emphasis mine)

Code Snippets

(event.target as HTMLInputElement).value

Context

Stack Overflow Q#44321326, score: 521

Revisions (0)

No revisions yet.