どのように私は活字を使って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 => {

私はオンラインこの問題を有する複数の人を見ましたが、私は詳細な解決策を見つけることができませんでした

hoangdv:

カスタムインターフェイスを作成する- ExtWebSocketインタフェースが拡張されますWebSocket次に、あなたをキャストsocketとして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
  })
});

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=369615&siteId=1