Issue
I am working on a Typescript Websocket Project, where the client connects to Backend using Websocket connections.
So obviously typescript will give type hints about the Websocket and its on
callbacks like, onclose, onmessage, etc.
Take onmessage
now. onmessage
type signature is (this: WebSocket, ev: MessageEvent<any>) => any
(I just directly copied from vscode hints).
So first parameter is this
of type WebSocket
, i.e that same instance.
Second parameter is ev
of type MessageEvent
.
If I need the MessageEvent
, I should pass the function as
ws.onmessage = function (this: WebSocket, ev: MessageEvent<any>) {
console.log("Event", ev);
}
Yes, as expected above code works.
But, the below code also works.
ws.onmessage = function (ev: MessageEvent<any>) {
console.log("Event", ev);
}
Even the Typescript is getting compiled to JS, so there is no way there can be any kind of method overloading happened in this case. (Like in JAVA).
How onmessage
knows to pass the event to my function:
- as second param when there are two params.
- as first param when there is one param.
Solution
This is a feature of Typescript. Typescript docs.
The this
from the first param will be stripped during transpiling.
You can see the transpiling using Babel Repl. So the onmessage callback wont know if the function has two or one param.
Note: this
in function param throws an error.
Answered By - Sanjay S
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.