J.B*_*B.C 2 socket.io typescript
我正在使用带有打字稿的 Socket.io v4.0.1 和按预期工作的节点/快速服务器。问题是,在连接时,我想向客户端套接字发送它的 sessionID 和 userID,它们是我的服务器套接字实例上的附加属性,但 typescript 抛出以下类型错误。
io.on("connection", (socket: Socket): void => {
console.log(socket.id);
socket.emit("session", {
sessionID: socket.sessionID, // property sessionID does not exist on type Socket<DefaultEventsMap,DefaultEventsMap>
userID: socket.userID,// property userID does not exist on type Socket<DefaultEventsMap,DefaultEventsMap>
});
});
Run Code Online (Sandbox Code Playgroud)
有没有办法在不改变类型定义本身(@types/socket.io)的情况下将这些附加属性添加到类型定义中?
解决方案是创建我自己的接口,它扩展了 Socket 类型并添加了所需的附加属性。
interface ISocket extends Socket {
name?: string;
// other additional attributes here, example:
// surname?: string;
}
Run Code Online (Sandbox Code Playgroud)
虽然我已经尝试过,但它给我带来了另一个错误,基本上是类型Socket
和ISocket
不能兼容,因为属性“名称”在 type 中丢失而在 type 中是Socket
必需的ISocket
。
该问题的解决方案是添加“?” 在name?: string
。这使得界面中不需要该字段。
感谢@halilcakar 帮助我。
归档时间: |
|
查看次数: |
525 次 |
最近记录: |