Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

npm包ws,怎么在连接上添加自定义属性?

import WebSocket from 'ws';
global.WebsocketServer = new WebSocket.Server({ server });

global.WebsocketServer.on('connection', (socket, request) => {
    socket.attempt = ...
});

然后ts报:类型“WebSocket”上不存在属性“attempt”,我知道这只是ts的检查,实际运行这样没问题,但是我想把attempt纳入ts的代码检查范围,规避不必要的bug,在ws官方定的的d.ts中

declare namespace WebSocket {
    ...
    
    class Server extends events.EventEmitter {
        ...
        on(event: 'connection', cb: (this: Server, socket: WebSocket, request: http.IncomingMessage) => void): this;
        ...
    }
    
    ...
}

connection里定义的socket: WebSocket里面的WebSocket是一个class

declare class WebSocket extends events.EventEmitter {
    ...
}

并且这个class没有在namespace WebSocket中,现在报类型“WebSocket”上不存在属性“attempt”显然是class WebSocket上没有attempt,这个好像也没法用ts的类型合并啊。
问:怎么在自己的d.ts中为WebSocket加入attempt的定义,路过的大神请帮忙看看,谢谢!!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

这是我现在的解决办法,有点蠢(是个ts文件):
websocket.ts

import WebSocket from 'ws';

interface MyWebSocket extends WebSocket {
    attempt: SocketAttempt
    ...
}

class WebSocketServer extends WebSocket.Server {
    constructor(_options?: WebSocket.ServerOptions, _callback?: (() => void)) {
        super(_options, _callback);
    }

    connection(cb: (socket: MyWebSocket, request: http.IncomingMessage) => void): void {
        this.on('connection', cb);
    }
}

export { WebSocketServer };

然后:

import { WebSocketServer } from './websocket';

global.WebsocketServer = new WebSocketServer({ server });

global.WebsocketServer.connection((socket, request) => {
    socket.attempt = ...
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...