TypeScript and Socket.io

39,849

Solution 1

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

npm i --save @types/socket.io

Solution 2

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

Solution 3

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");

Solution 4

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

const client: SocketIOClient.Socket = io('http://localhost');
Share:
39,849
lhk
Author by

lhk

Updated on July 16, 2020

Comments

  • lhk
    lhk almost 4 years

    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/typescript-node-definitions/blob/master/socket.io.d.ts

    It shows how to use TypeScript in combination with Socket.io. However on the client side it uses JavaScript.

    What I need is a .d.ts file for client-side TypeScript, that resolves the error message from this line:

    var socket=io.connect("localhost");
    

    The name "io" does not exist in the current scope

    Where can I find the appropriate definition file?

  • sintetico82
    sintetico82 about 6 years
    For the client side: npm i --save @types/socket.io-client
  • Ahmed Fasih
    Ahmed Fasih over 3 years
    What @sintetico82 said above is solid: npm i --save-dev @types/socket.io-client (save-dev is ok if your HTML will load the JavaScript payload from the SocketIO server), then in your TypeScript code const socket=io(); will be automatically typed: const socket: SocketIOClient.Socket.
  • idunno
    idunno over 2 years
    NOTE: @types/socket.io-client is a stub types definition. socket.io-client provides its own type definitions, so you do not need it installed.