我在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);
}
}现在我试着使用打字本,我得到了这些错误:
focus()函数:(parameter) key: string
Type 'Element | {} | null' has no matching index signature for type 'string'. ts(2537)ACTIONS对象上:Property 'click' does not exist on type 'EventTarget'. ts(2339)我如何纠正这些错误?
发布于 2021-03-15 19:14:36
问题
activeElement是DOM中的当前活动元素。如果没有active元素,则其值为null。null不能像使用{[key]: elementSibling}那样使用索引签名。此外,activeElement的类型是Element | null (元素)。Element没有定义任何索引签名,这意味着我们不能通过任意的string键索引activeElement。
问题,点击-首先,任何作为目标属性的EventTarget | null (参考)类型的事件。因此,e.target也可以是null。其次,EventTarget是通用接口。它没有click方法。您需要将其键入到HTMLInputElement。
解决方案
若要将key从任何字符串中删除,请将文本类型添加为'nextElementSibling' | 'previousElementSibling'并使用可选链。
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);
}
}https://stackoverflow.com/questions/66643784
复制相似问题