使用带有 Angular 的 FromEvent RxJS 订阅输入标签值更改时,如何避免使用 'any'?

How to avoid using 'any' when using FromEvent RxJS with Angular to subscribe to input tag value changes?

我无法在使用 FromEventsRxJS 时定义特定类型。当我通过管道传输 'keyup' 事件并将其映射以获取输入值时,我只能使用 (e: any => return (e.target!).value;)。即使浏览器的调试器将 e 识别为 KeyboardEvent,如果我定义 e: KeyboardEvent,我也会收到一条错误消息,指出“e 不包含 属性 目标”。然而,当前代码有效,因为我是 RxJS + Angular 的新手,社区总是建议避免使用 any,所以我想知道在这种情况下我该怎么做才能避免使用它?

Component.ts

import { TagInterface } from './../../../interfaces/tag/tag-interface';
import { Component, OnInit, Output, EventEmitter, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { debounceTime, distinctUntilChanged, filter, map } from 'rxjs/operators';
import { fromEvent, Observable } from 'rxjs';


@Component({
  selector: 'app-tag-search-bar',
  templateUrl: './tag-search-bar.component.html',
  styleUrls: ['./tag-search-bar.component.scss']
})
export class TagSearchBarComponent implements OnInit,AfterViewInit {

  @Output() tags = new EventEmitter<TagInterface[]>();
  @ViewChild('tagInput') tagInputChild!: ElementRef;

  mappedAndFilteredInput!: Observable<any>;
  eventKeyUp! : Observable<any>;

  constructor() { }

  ngOnInit(): void {
  }

  ngAfterViewInit() {
    this.eventKeyUp = fromEvent(this.tagInputChild.nativeElement, 'keyup');
    this.mappedAndFilteredInput = this.eventKeyUp.pipe(
      map((e: any) => {
        return (e.target!).value;
      }),
      debounceTime(100),
      distinctUntilChanged(),
      filter(value => (value != "" && value != undefined)) 
    );

    this.mappedAndFilteredInput.subscribe(
      value => console.log(value),
      error => console.log(`error: ${error}`),
      () => console.log('completed maping and filtering tag input term'));
  }
}

HTML

<div class="input-group-prepend">
    <span class="input-group-text">
        <i class="far fa-filter"></i>
    </span>
</div>
<input #tagInput type="text" class="filter-tag-list">

这是从 KeyboardEvent

中获取 target 的类型安全方法
    fromEvent<KeyboardEvent>(document.documentElement, 'keyup').subscribe(e => {
      const [target] = e.composedPath()
      console.log(target)      
    })

但是,在您的情况下,这样做会更简单

fromEvent(this.tagInputChild.nativeElement, 'keyup').subscribe(_ => {
  console.log(this.tagInputChild.nativeElement.value)
})

或者最好还是使用表单控件,并在表单控件上监听 valueChanges。