Javascript TypeScript 和 Socket.io
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14084406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript and Socket.io
提问by lhk
I would like to use socket.io in my Typescript project, but I've only found .d.ts files for server-side typescript.
我想在我的 Typescript 项目中使用 socket.io,但我只找到了用于服务器端打字稿的 .d.ts 文件。
This is a nice example: https://github.com/soywiz/typescript-node-definitions/blob/master/socket.io.d.ts
这是一个很好的例子: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.
它展示了如何将 TypeScript 与 Socket.io 结合使用。但是在客户端它使用 JavaScript。
What I need is a .d.ts file for client-side TypeScript, that resolves the error message from this line:
我需要的是客户端 TypeScript 的 .d.ts 文件,它解决了这一行的错误消息:
var socket=io.connect("localhost");
The name "io" does not exist in the current scope
当前作用域中不存在名称“io”
Where can I find the appropriate definition file?
在哪里可以找到合适的定义文件?
回答by Nick D
There is @types/socket.io now, just install it by running:
现在有@types/socket.io,只需通过运行安装它:
npm i --save @types/socket.io
npm i --save @types/socket.io
回答by bennyl
You should use socket.io-clientd.ts file in the client and while using socket.iod.ts file on the server.
您应该使用socket.io客户端在客户端,同时使用d.ts文件socket.io服务器上d.ts文件。
回答by lhk
I created my own .d.ts file, it's rather short but it works well:
我创建了自己的 .d.ts 文件,它很短,但效果很好:
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:
这个声明文件可以导入客户端 Typescript 并且 socket.io 标准示例将工作,这是我的 Typescript 版本:
var socket=io.connect("localhost");
socket.on("news",(data:any)=>alert(data));
socket.emit("news","hello");

