最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - KeyboardEvent: Property 'value' does not exist on type 'EventTarget' - Stack Overfl

programmeradmin1浏览0评论

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

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
});
Share Improve this question edited Mar 19, 2019 at 13:07 Hermann.Gruber 1,4841 gold badge16 silver badges45 bronze badges asked Dec 31, 2018 at 13:17 mattmatt 7492 gold badges9 silver badges17 bronze badges 4
  • What is the type of EventTarget here ? – Sachin Gupta Commented Dec 31, 2018 at 13:19
  • 1 input element.... – matt Commented Dec 31, 2018 at 13:24
  • Can you provide a MCVE? Can't reproduce the issue on my side. – Nino Filiu Commented Dec 31, 2018 at 13:37
  • @matt Is the problem solved? – Saddam Pojee Commented Jan 6, 2019 at 13:14
Add a comment  | 

2 Answers 2

Reset to default 15

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.

Try to use this kinda typing, istead of KeyboardEvent use ChangeEvent:

map((e: React.ChangeEvent<HTMLInputElement>) => e.target.value),
发布评论

评论列表(0)

  1. 暂无评论