react-use-websocket icon indicating copy to clipboard operation
react-use-websocket copied to clipboard

Specify Type of SendJsonMessage correctly

Open hellow554 opened this issue 2 years ago • 1 comments
trafficstars

Currently, we have this arrangement of types https://github.com/robtaussig/react-use-websocket/blob/0d9444df3a143bd3bec5fead7fdb05f7a00f9908/src/lib/types.ts#L62-L69

The problem is, that we T is not forwarded to the sendJsonMessage member. If we try, we get an error: Type 'SendJsonMessage' is not generic., to fix that we can change https://github.com/robtaussig/react-use-websocket/blob/0d9444df3a143bd3bec5fead7fdb05f7a00f9908/src/lib/types.ts#L52

from type SendJsonMessage = <T = unknown>(...) to type SendJsonMessage<T = unknown> = (...) (note the position of the = sign).

So my first question is:

  1. Was this an oversight?
  2. Would sendJsonMessage: SendJsonMessage<T> a proper fix, or should we allow different types for sendJsonMessage and lastJsonMessage, e.g.:
export type WebSocketHook<Ret = unknown, Send = Ret, P = WebSocketEventMap['message'] | null> = {
  sendMessage: SendMessage,
  sendJsonMessage: SendJsonMessage<Send>,
  lastMessage: P,
  lastJsonMessage: Ret,
  readyState: ReadyState,
  getWebSocket: () => (WebSocketLike | null),
}

(also update useWebSocket of course)

Here's a small playground I created to test this: Playground Link

hellow554 avatar Oct 30 '23 10:10 hellow554