'Correctly type event handler in Typescript for a react hook
I am doing a socket.io implementation in typescript.
I have the following event map:
type User {
id: string
name: string
}
interface EventsMap {
'user:created': UserEvent<User>
'user:deleted': UserEvent<string>
}
const socket: Socket<EventsMap, DefaultEventsMap> = io('http://example.com')
And the hook I wish to create looks like this:
export function useSocketEvent(
eventName: keyof EventsMap,
handler: any,
) {
...
useEffect(() => {
socket.on(eventName, handler)
return () => {
socket.off(eventName, handler)
}
}, [eventName, handler])
}
I am not sure what is the correct way to type the handlerin the hook so that that type would be correctly linked to the first arg of the hook - the eventName.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
