ElementRef<any>.nativeElement:任何抛出 "Unsafe call of an any typed value" 错误

ElementRef<any>.nativeElement: any throwing "Unsafe call of an any typed value" error

我有以下指令阻止将任何字母数字字符输入到字段中。

在 validateFields 方法中,ESLint 抛出以下错误消息:

ESLint: Unsafe call of an any typed value.(@typescript-eslint/no-unsafe-call)

我查看了 ElementRef 的类型,它具有以下属性:

ElementRef<any>.nativeElement: any

考虑到这一点,我该如何解决以下问题。

@Directive({
  selector: '[appBlockNonAlphanumericCharacters]',
})
export class BlockNonAlphanumericCharactersDirective {
  @Input() isAlphaNumeric = true;

  regex = '^[a-zA-Z0-9_-]*$';

  constructor(private elementRef: ElementRef) {}

  @HostListener('keypress', ['$event']) onKeyPress(event: KeyboardEvent): boolean {
    return new RegExp(this.regex).test(event.key);
  }

  @HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent): void {
    this.validateFields(event);
  }

  validateFields(event: KeyboardEvent): void {
    setTimeout(() => {
      if (this.elementRef.nativeElement) {
      // Error thrown here - ESLint: Unsafe member access ['value'] on an any value.(@typescript-eslint/no-unsafe-member-access)
        this.elementRef.nativeElement['value'] = this.elementRef.nativeElement['value']
          .replace(/[^A-Za-z ]/g, '')
          .replace(/\s/g, '') as string;
      }
      event.preventDefault();
    }, 100);
  }
}

您需要声明 nativeElement 的类型。由于 ElementRef 接受一个类型(这将是 nativeElement 的类型),最好的方法是像这样注入:

private elementRef: ElementRef<HTMLElement>