TypeScript和Socket.io [英] TypeScript and Socket.io

查看:1222
本文介绍了TypeScript和Socket.io的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的Typescript项目中使用socket.io,但我只找到服务器端打字稿的.d.ts文件。

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

这是一个很好的例子: https://github.com /soywiz/typescript-node-definitions/blob/master/socket.io.d.ts

This is a nice example: https://github.com/soywiz/typescript-node-definitions/blob/master/socket.io.d.ts

它显示了如何将TypeScript与Socket结合使用。 IO。但是在客户端它使用JavaScript。

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

我需要的是客户端TypeScript的.d.ts文件,它解决了这一行的错误信息: / p>

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




当前范围内不存在名称io

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

我在哪里可以找到合适的定义文件?

Where can I find the appropriate definition file?

推荐答案

我创建了自己的.d.ts文件,它很短但效果很好:

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

此声明文件可导入客户端Typescript和socket.io标准示例将起作用,这是我的Typescript版本:

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

这篇关于TypeScript和Socket.io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆