[英]TS error: Type 'event' is missing the following properties from type 'keyboardevent'
I have a custom event listener hook that looks like this:我有一个自定义事件监听器钩子,如下所示:
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])
}
This is throwing the error,这是抛出错误,
TS error: Type 'event' is missing the following properties from type 'keyboardevent': char, key and 18 others
Am I typing the useRef incorrectly?我输入的 useRef 不正确吗? I wasn't able to find anything from here that work either.
我也无法从这里找到任何有用的东西。 Not sure what I'm doing wrong here.
不知道我在这里做错了什么。
It's OK.没关系。
Working solutions will be工作解决方案将是
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])
}
The issue was eventName: string,
问题是
eventName: string,
TS sees that you are allowing to listen for any event (keyboard or not) so it can't guarantee that the emitted event will be only keyboard type. TS 看到您允许侦听任何事件(键盘与否),因此它不能保证发出的事件将只是键盘类型。 So you need to assure TS that you will listen only for keyboard events.
所以你需要向 TS 保证你只会监听键盘事件。 This can be done by providing the correct type for the eventName which should be a subset of the keyboard event names.
这可以通过为 eventName 提供正确的类型来完成,该类型应该是键盘事件名称的子集。
That's it.而已。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.