gpt4 book ai didi

javascript - TS 错误 : Type 'event' is missing the following properties from type 'keyboardevent'

转载 作者:行者123 更新时间:2023-12-04 11:36:07 25 4
gpt4 key购买 nike

我有一个自定义事件监听器钩子(Hook),如下所示:

const useEventListener = (
eventName: string,
handler: ({key} : KeyboardEvent) => void,
) => {
const savedHandler = useRef<({key} : KeyboardEvent) => void>(handler)

useEffect(() => {
savedHandler.current = handler
}, [handler])

useEffect(() => {
const eventListener = (event: KeyboardEvent) => savedHandler.current(event)

window.addEventListener(eventName, eventListener);

return () => {
window.removeEventListener(eventName, eventListener)
}
}, [eventName])
}
这是抛出错误,
TS error: Type 'event' is missing the following properties from type 'keyboardevent': char, key and 18 others
我输入的 useRef 不正确吗?我无法从 here 中找到任何内容那也行。不知道我在这里做错了什么。

最佳答案

没关系。
工作解决方案将是

const useEventListener = (
eventName: 'keydown' | 'keyup',
handler: ({key} : KeyboardEvent) => void,
) => {
const savedHandler = useRef<({key} : KeyboardEvent) => void>(handler)

useEffect(() => {
savedHandler.current = handler
}, [handler])

useEffect(() => {
const eventListener = (event: KeyboardEvent) => savedHandler.current(event)

window.addEventListener(eventName, eventListener);

return () => {
window.removeEventListener(eventName, eventListener)
}
}, [eventName])
}

问题是 eventName: string,TS 看到您允许监听任何事件(键盘与否),因此它不能保证发出的事件将是 仅限 键盘类型。所以你需要向 TS 保证你只会监听键盘事件。这可以通过为 eventName 提供正确的类型来完成,该类型应该是键盘事件名称的子集。
而已。

关于javascript - TS 错误 : Type 'event' is missing the following properties from type 'keyboardevent' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62929308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com