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

Viewed 7808

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

Related