Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 在TypeScript中表达ws-alternative_Node.js_Typescript_Websocket - Fatal编程技术网

Node.js 在TypeScript中表达ws-alternative

Node.js 在TypeScript中表达ws-alternative,node.js,typescript,websocket,Node.js,Typescript,Websocket,我已经搜索了几天了,但仍然没有找到任何替代方案或帮助为它编写一个TypeScript声明,因为我也尝试过 重要的是,它可以与express中的任何其他路线一起使用。身份验证、角色和路径参数。唯一的问题是路由器类型没有ws(…)方法。加 export interface RouterWs extends express.Router { ws (route: string, ...cb): RouterWs; } 然后,在获取路由器时,只需将其转换为您的类型 const router =

我已经搜索了几天了,但仍然没有找到任何替代方案或帮助为它编写一个TypeScript声明,因为我也尝试过


重要的是,它可以与express中的任何其他路线一起使用。身份验证、角色和路径参数。

唯一的问题是
路由器
类型没有
ws(…)
方法。加

export interface RouterWs extends express.Router {
  ws (route: string, ...cb): RouterWs; 
}
然后,在获取
路由器时,只需将其转换为您的类型

const router = express.Router() as RouterWs;
router.ws('/somepath', (ws, req) => {...

express ws的打字现在已经完成

演示如何使用它:

import expressWs from 'express-ws';
const { app, getWss, applyTo } = expressWs(express());
或:

然后,例如,当声明路由而不是写入时:

const myRoutes = function(app: Express) {...}
您需要指定express ws类型:

import expressWs from 'express-ws';
const myRoutes = function(app: expressWs.Application) {...}

感谢德里克·希尔和诺蒙兹·卡恩贝津斯

使用路由器更好

首次导入express ws

import expressWs from 'express-ws';
要使用
ws
方法,需要加强express(我是这样理解的)

之后
express.Router
包含
ws
方法,但是类型脚本的类型错误,您只需要转换类型

const router = express.Router() as expressWs.Router;
定义路由逻辑

router.ws('/echo', (ws, req) => {
    ws.on('message', (msg: String) => {
        ws.send(msg);
    });
});
最后将
路由器
添加到express
应用程序

app.use("/ws-stuff", router);
router.ws('/echo', (ws, req) => {
    ws.on('message', (msg: String) => {
        ws.send(msg);
    });
});
app.use("/ws-stuff", router);