TypeScript and Socket.io

2019-03-21 00:10发布

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?

3条回答
该账号已被封号
2楼-- · 2019-03-21 01:01

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

npm i --save @types/socket.io

查看更多
叼着烟拽天下
3楼-- · 2019-03-21 01:12

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");
查看更多
女痞
4楼-- · 2019-03-21 01:13

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

查看更多
登录 后发表回答