fastify-websocket
fastify-websocket copied to clipboard
`@types/ws` is missing which results in loosing typing withing handler
Prerequisites
- [X] I have written a descriptive issue title
- [X] I have searched existing issues to ensure the bug has not already been reported
Fastify version
4.27.0
Plugin version
10.0.1
Node.js version
20.12.2
Operating system
Windows
Operating system version (i.e. 20.04, 11.3, 10)
10
Description
When using this plugin with TypeScript the socket within the handler isn't typed correctly because it reexports WebSocket.WebSocket from ws which isn't listed as a dependency.
app.get('/new-status-route', {websocket: true}, async (socket, req) => {
// socket is any instead of WebSocket.WebSocket
Therefore it's necessary to install it additionally.
I think the typical solution would be listing it in dependencies rathern than devDependencies.
Link to code that reproduces the bug
No response
Expected Behavior
The plugin also installs @types/ws which leads to the correct type of socket within the handler.
This is as at odds with devs wanting less modules in production, and there is no way to achieve boths.
I think this covers the scenario well: https://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html
Our package exposes declarations from each of those, so any user of our browserify-typescript-extension package needs to have these dependencies as well. For that reason, we used "dependencies" and not "devDependencies", because otherwise our consumers would have needed to manually install those packages.
I totally agree that having to install fewer modules in production is a good thing, however besides the additional module that needs to be installed the amount of code is quite similar in comparison with a package that already has type definitions included.
I'm not sure if this is related but I cannot get any TypeScript autocompletes for fastifyInstance.websocketServer even though TypeScript knows the type WebSocket.Server...
(No autocomplete is shown when I type api.websocketServer......)
However, if I do this it works import WebSocket from "ws"; ... (api.websocketServer as WebSocket.Server).close()
Meanwhile the type completions for other @fastify/websocket decorations are working such as api.injectWS
I worked around my own issue with module augmentation and a new decorator...
declare module "fastify" {
export interface FastifyInstance {
get wss(): import("ws").WebSocketServer;
}
}
fastifyInstance.decorate("wss", {
getter() {
return this.websocketServer;
},
});
Now I get type completions for fastifyInstance.wss...