javascript - KeyboardEvent: 'value' özelliği 'EventTarget' türünde mevcut değil


Angular'ın sayfasından bazı kodları kopyaladım ve Visual Studio Code bir hata gösteriyor:

Bu satır için hata:

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

Hata

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

Angular web sitesinden kod:

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

Cevap #1

Typescript etkinlik türünü çıkaramayacağından, hedefiniz olan HTMLElement’in türünü açıkça yazmanız gerekir. Örneğin, türü HTMLInputElement ise, aşağıdaki satırı yazabilirsiniz:

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

Bu, problemini çözecek.

İlgili makaleler