在打字稿中保存 socket.io 对象的更多数据

Anu*_*nup 7 node.js socket.io typescript typescript-typings

socket.username = username我通常在不使用打字稿时做类似的事情。但现在我是这样,当我尝试以同样的方式保存它时,它给了我错误

Property 'username' does not exist on type 'Socket'
Run Code Online (Sandbox Code Playgroud)

我知道这意味着我需要扩展它,但我已经尝试过像这样

interface Socket {
        username: any
}
Run Code Online (Sandbox Code Playgroud)

但这没有帮助,我也尝试过这个,

interface SocketIO {
        username: any
}
Run Code Online (Sandbox Code Playgroud)

没有运气。

Tsv*_*nev 7

只是socket['username'] = username应该做的伎俩。

如果您希望类型安全并且希望属性具有自动完成功能username,则可以扩展该Socket接口。

interface ExtendedSocket extends Socket {
  username: string;
}
Run Code Online (Sandbox Code Playgroud)

然后您可以将原始类型转换Socket为您的自定义类型:

const mySocket = <ExtendedSocket>socket;
mySocket.username = 'user1'; // won't throw errors and autocomplete will work
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您想向套接字对象添加额外的信息,您可以将此信息添加到在其声明文件中socket.data声明的对象中any

socket.d.ts以下是文件的片段

/**
* Additional information that can be attached to the Socket instance and which will be used in the fetchSockets method
*/
data: any;
Run Code Online (Sandbox Code Playgroud)