TypeScript and Socket.io

前端 未结 4 2092
伪装坚强ぢ
伪装坚强ぢ 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");
    

提交回复
热议问题