fastify / fastify-websocket

basic websocket support for fastify
MIT License
392 stars 72 forks source link

`@types/ws` is missing which results in loosing typing withing handler #300

Open cyantree opened 2 months ago

cyantree commented 2 months ago

Prerequisites

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.

mcollina commented 2 months ago

This is as at odds with devs wanting less modules in production, and there is no way to achieve boths.

cyantree commented 2 months ago

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.

waynesbrain commented 4 days ago

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...

image

(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()

image

Meanwhile the type completions for other @fastify/websocket decorations are working such as api.injectWS

waynesbrain commented 4 days ago

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...