You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
IMO one type T for sendJsonMessage and lastJsonMessage would have very little use, because it would mean that your sent and received messages need to be of the same type, which is rarely the case. I think separate send and receive types are the way to go here.
Right now I am trying to narrow the type down to make sending more type-safe, but it is pretty verbose and I am struggling to come up with better alternatives:
import{WebSocketHook}from"react-use-websocket/dist/lib/types";exporttypeTypedWebSocketHook<TRecv=unknown,TSend=unknown>=Omit<WebSocketHook<TRecv>,"sendJsonMessage">&{sendJsonMessage: (message: TSend,keep?: boolean)=>void};// used astypeRecvMsg="OK"|{data: number};typeSentMsg="stop"|{some_test_param: number};typeSafeWebSocket=TypedWebSocketHook<RecvMsg,SentMessage>;const{ lastJsonMessage, sendJsonMessage, readyState }=useWebSocket(...)asTypeSafeWebSocket;// and when passing to componentsinterfaceComponentProps{sendJsonMessage: SafeWebSocket["sendJsonMessage"]}
Without it we need to jump through weird hoops to ensure the outgoing message is of expected shape.
Currently, we have this arrangement of types
react-use-websocket/src/lib/types.ts
Lines 62 to 69 in 0d9444d
The problem is, that we
T
is not forwarded to thesendJsonMessage
member. If we try, we get an error:Type 'SendJsonMessage' is not generic.
, to fix that we can changereact-use-websocket/src/lib/types.ts
Line 52 in 0d9444d
from
type SendJsonMessage = <T = unknown>(...)
totype SendJsonMessage<T = unknown> = (...)
(note the position of the=
sign).So my first question is:
sendJsonMessage: SendJsonMessage<T>
a proper fix, or should we allow different types forsendJsonMessage
andlastJsonMessage
, e.g.:(also update
useWebSocket
of course)Here's a small playground I created to test this: Playground Link
The text was updated successfully, but these errors were encountered: