Socket.io 打字稿上的附加属性不存在

Socket.io additional attributes on typescript do not exist

我正在使用带有打字稿的 Socket.io v4.0.1 和按预期工作的 node/express 服务器。 问题是在连接时我想向客户端套接字发送它的 sessionID 和 userID,它们是我的服务器套接字实例上的附加属性,但是打字稿抛出以下类型错误。

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

有没有办法在不更改类型定义本身的情况下将这些附加属性添加到类型定义中 (@types/socket.io)?

socketio's additional attributes documentation

解决方案是创建我自己的接口,它从 Socket 类型扩展并添加所需的附加属性。

interface ISocket extends Socket {
  name?: string;
  // other additional attributes here, example:
  // surname?: string;
}

虽然我已经试过了,但它又给我带来了另一个错误,基本上是说 SocketISocket 类型不兼容,因为 属性 “名称”在类型 Socket 中缺失,在类型 ISocket 中需要。

该问题的解决方案是添加“?”在 name?: string。这使得界面中不需要该字段。

感谢@halilcakar 帮助我。

尝试扩展套接字接口:

declare module 'socket.io' {
  interface Socket {
    sessionID?: string;
    userID?: string;
    // other additional attributes here, example:
    // surname?: string;
  }
}

...

io.on("connection", (socket: Socket): void => {
  console.log(socket.id);

  socket.emit("session", {
    sessionID: socket.sessionID,  // OK
    userID: socket.userID,        // OK
  });
});