"Error is Property 'focus' does not exist on type 'EventTarget'.ts":焦点无法在文档、querySelector 中工作

"Error is Property 'focus' does not exist on type 'EventTarget'.ts" : focus is not bale to work in document,querySelector

为什么焦点出错?错误是 属性 'focus' 在类型 'EventTarget'.ts

上不存在

谁能帮帮我

@HostListener('keydown.tab', [ '$event'])
 keyfunction(event: KeyboardEvent): void {
   // First element: always first element is h2 where tabindex avaliable.
   let focusable = document.querySelector('.modal').querySelectorAll('[tabindex],button');
   if (focusable.length) {
       const first = focusable[0];
       const last = focusable[focusable.length - 1];
       const shift = event.shiftKey;
    
       if (shift) {
         if (event.target === first) {
           last.focus();// **Error is: Error is Property 'focus' does not exist on type **
           
           event.preventDefault();
         }
     } else {
         if (event.target === last) {
            first.focus();// Getting error is here
           event.preventDefault();
         }
       }
     }

lastfirst 默认类型为 Element 因为 querySelectorAll returns 类型 NodeListOf<Element>.

的值

我的建议是在声明时更改类型。

const first: HTMLElement = focusable[0] as HTMLElement;
const last: HTMLElement = focusable[focusable.length - 1] as HTMLElement;