首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何修复document.activeElement上"Type‘元素{} {} null’没有匹配的'string‘类型索引签名?

如何修复document.activeElement上"Type‘元素{} {} null’没有匹配的'string‘类型索引签名?
EN

Stack Overflow用户
提问于 2021-03-15 18:42:16
回答 1查看 210关注 0票数 0

我在javascript项目中使用了这个令人惊奇的代码

代码语言:javascript
复制
function focus(key: string){
  const {activeElement:{[key]: elementSibling} = {}} = document;
  if(elementSibling){
    elementSibling.focus();
  }
}

const ACTIONS: { [key: string]: (e: KeyboardEvent) => void } = {
  ArrowDown: (): void => focus('nextElementSibling'),
  ArrowUp: (): void => focus('previousElementSibling'),
  Enter: (e: KeyboardEvent): void => e.target.click()
}

function handleKeyDown(e: KeyboardEvent): void {
  const handler = ACTIONS[e.key];
  if(handler) {
    e.preventDefault();
    handler(e);
  }
}

现在我试着使用打字本,我得到了这些错误:

  1. 关于focus()函数:
代码语言:javascript
复制
(parameter) key: string
Type 'Element | {} | null' has no matching index signature for type 'string'. ts(2537)
  1. ACTIONS对象上:
代码语言:javascript
复制
Property 'click' does not exist on type 'EventTarget'. ts(2339)

我如何纠正这些错误?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-15 19:14:36

问题

activeElement是DOM中的当前活动元素。如果没有active元素,则其值为nullnull不能像使用{[key]: elementSibling}那样使用索引签名。此外,activeElement的类型是Element | null (元素)。Element没有定义任何索引签名,这意味着我们不能通过任意的string键索引activeElement

问题,点击-首先,任何作为目标属性的EventTarget | null (参考)类型的事件。因此,e.target也可以是null。其次,EventTarget是通用接口。它没有click方法。您需要将其键入到HTMLInputElement

解决方案

若要将key从任何字符串中删除,请将文本类型添加为'nextElementSibling' | 'previousElementSibling'并使用可选链

代码语言:javascript
复制
function focus(key: 'nextElementSibling' | 'previousElementSibling'){
  const {activeElement} = document
  const elementSibling = activeElement?.[key] as (HTMLInputElement | null)
  if(elementSibling){
    elementSibling.focus()
  }
}

const ACTIONS = {
  ArrowDown: () => focus('nextElementSibling'),
  ArrowUp: () => focus('previousElementSibling'),
  Enter: handleEnterKeyEvent
}

function handleEnterKeyEvent(e: KeyboardEvent) {
  const target = e.target as (HTMLInputElement | null)
  target?.click()
}

function handleKeyDown (e: KeyboardEvent) {
  const handler = (<any>ACTIONS)[e.key];
  if(handler) {
    e.preventDefault();
    handler(e);
  }
}

游乐场

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66643784

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档