[javascript] Property 'value' does not exist on type EventTarget in TypeScript

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:

<input type="text" class="form-control" (input)="onUpdatingServerName($event)">

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.

This question is related to javascript angular typescript

The answer is


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

I was looking for a solution to a similar TypeScript error with React:

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

I wanted to get to event.target.dataset of a clicked button element in React:

<button
  onClick={onClickHandler}
  data-index="4"
  data-name="Foo Bar"
>
  Delete Candidate
</button>

Here is how I was able to get the dataset value to "exist" via TypeScript:

const onClickHandler = (event: React.MouseEvent<HTMLButtonElement>) => {
  const { name, index } = (event.target as HTMLButtonElement).dataset
  console.log({ name, index })
  // do stuff with name and index…
}

You should use event.target.value prop with onChange handler if not you could see :

index.js:1437 Warning: Failed prop type: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.

Or If you want to use other handler than onChange, use event.currentTarget.value


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.


add any type to event

event: any

example

[element].addEvenListener('mousemove', (event: any) =>{
//CODE//
} )

what happens is that typescript adds event as Event type and for some reason it doesn't recognize some properties. Adding it of type any no longer exists this problem, this works for any document.[Property]


Try code below:

  console.log(event['target'].value)

it works for me :-)


you can also create your own interface as well.

    export interface UserEvent {
      target: HTMLInputElement;
    }

       ...

    onUpdatingServerName(event: UserEvent) {
      .....
    }

The way I do it is the following (better than type assertion imho):

onFieldUpdate(event: { target: HTMLInputElement }) {
  this.$emit('onFieldUpdate', event.target.value);
}

This assumes you are only interested in the target property, which is the most common case. If you need to access the other properties of event, a more comprehensive solution involves using the & type intersection operator:

event: Event & { target: HTMLInputElement }

This is a Vue.js version but the concept applies to all frameworks. Obviously you can go more specific and instead of using a general HTMLInputElement you can use e.g. HTMLTextAreaElement for textareas.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?