Property 'value' does not exist on type EventTarget in TypeScript
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 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.[...]
The
$event
is now a specificKeyboardEvent
. Not all elements have avalue
property so it caststarget
to an input element.
(Emphasis mine)
Here's another fix that works for me:
(event.target as HTMLInputElement).value
That should get rid of the error by letting TS know that event.target
is an HTMLInputElement
, which inherently has a value
. Before specifying, TS likely only knew that event
alone was an HTMLInputElement
, thus according to TS the keyed-in target
was some randomly mapped value that could be anything.
Passing HTMLInputElement as a generic to the event type should work too:
onUpdatingServerName(event: React.ChangeEvent<HTMLInputElement>) {
console.log(event);
this.newserverName = event.target.value;
}