typescript - 如何使用 TypeScript 在 Node.js 中扩展 WebSocket 类型?
问题描述
我正在尝试扩展以下 WebSocket https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/ws/index.d.ts
无论我尝试什么,我似乎都无法向 WebSocket 添加新属性
// Messes with other typings in the WebSocket
declare module "ws" {
// Tried declare class MyWebSocket extends WebSocket too
interface WebSocket {
id: string;
}
}
wss.on("connection", socket => {
const id = uuidv4();
socket.id = id
socket.on("message", data => {
我在网上看到很多人有这个问题,但我找不到详细的解决方案
解决方案
创建一个自定义接口 -ExtWebSocket
接口将扩展WebSocket
。然后投你的socket
as ExtWebSocket
。没必要declare module
。
interface ExtWebSocket extends WebSocket {
id: string; // your custom property
}
用法
wss.on("connection", (socket: ExtWebSocket) => { // here
const id = uuidv4();
socket.id = id;
socket.on("message", data => {
// do something
})
});
推荐阅读
- android - 错误 - 以下启动画面或图标文件不存在:/res/icons/android/mipmap-hdpi/ic_launcher.png
- drupal - Drupal 站点因模块安装不当而损坏
- python - 使用类方法在 init 上检索或加载数据
- javascript - Oracle APEX 中 apex.server.process 的安全性
- javascript - 如何在 Vue 中从 graphql 数据集创建动态过滤?
- android - 如何从外部光栅化图像创建矢量资产而不获得“非常长的矢量路径”
- javascript - 如何在 Taiko JS 中编写异步动态下拉菜单
- c# - WPF:关注选项卡项更改的行为
- c# - 如何在单元测试中模拟字节数组中的假文件大小
- sql - 如何在聚合函数 SUM() 中替换 SELECTS