Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyboardEvent: Property 'value' does not exist on type 'EventTarget'

I've copied some code from Angular's page and visual code is showing an error:

Error for this line:

map((e: KeyboardEvent) => e.target.value),

Error

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

Code from Angular website:

import { fromEvent } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { map, filter, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';

const searchBox = document.getElementById('search-box');

const typeahead = fromEvent(searchBox, 'input').pipe(
  map((e: KeyboardEvent) => e.target.value),
  filter(text => text.length > 2),
  debounceTime(10),
  distinctUntilChanged(),
  switchMap(() => ajax('/api/endpoint'))
);

typeahead.subscribe(data => {
 // Handle the data from the API
});
like image 768
matt Avatar asked Dec 31 '18 13:12

matt


People also ask

How do you solve property value does not exist on type EventTarget?

js error "Property 'value' does not exist on type EventTarget" occurs when the type of the event parameter is incorrect. To solve the error, type the event as React. ChangeEvent<HTMLInputElement> . You can then access the value as event.

Does not exist on type EventTarget?

The error "Property 'value' does not exist on type 'EventTarget'" occurs when we try to access the value property on an element that has a type of EventTarget . To solve the error, use a type assertion to type the element correctly before accessing the property. This is the index.

What is EventTarget?

The EventTarget interface is implemented by objects that can receive events and may have listeners for them. In other words, any target of events implements the three methods associated with this interface.

What is the type of event target?

The target event property returns the element that triggered the event. The target property gets the element on which the event originally occurred, opposed to the currentTarget property, which always refers to the element whose event listener triggered the event.


1 Answers

Since, Typescript can't infer the event type. You need to explicitly write the type of the HTMLElement which is your target. For example, if its type is HTMLInputElement then you can write the below line:

map((e: KeyboardEvent) => (<HTMLInputElement>e.target).value),

This will solve your problem.

like image 86
Saddam Pojee Avatar answered Oct 05 '22 22:10

Saddam Pojee