TypeScript and Socket.io

前端 未结 4 2071
伪装坚强ぢ
伪装坚强ぢ 2021-02-04 15:08

I would like to use socket.io in my Typescript project, but I\'ve only found .d.ts files for server-side typescript.

This is a nice example: https://github.com/soywiz/ty

相关标签:
4条回答
  • 2021-02-04 15:41

    I created my own .d.ts file, it's rather short but it works well:

    declare var io : {
        connect(url: string): Socket;
    };
    interface Socket {
        on(event: string, callback: (data: any) => void );
        emit(event: string, data: any);
    }
    

    This declaration file can be imported to client side Typescript and the socket.io standard example will work, here's my Typescript version:

    var socket=io.connect("localhost");
    socket.on("news",(data:any)=>alert(data));
    socket.emit("news","hello");
    
    0 讨论(0)
  • 2021-02-04 15:50

    Inside @types/socket.io-client, you can find the following type which is best suited for clients:

    const client: SocketIOClient.Socket = io('http://localhost');
    
    0 讨论(0)
  • 2021-02-04 15:51

    There is @types/socket.io now, just install it by running:

    npm i --save @types/socket.io

    0 讨论(0)
  • 2021-02-04 15:55

    You should use socket.io-client d.ts file in the client and while using socket.io d.ts file on the server.

    0 讨论(0)
提交回复
热议问题