Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 在typescript中保存socket.io对象的更多数据_Node.js_Typescript_Socket.io_Typescript Typings - Fatal编程技术网

Node.js 在typescript中保存socket.io对象的更多数据

Node.js 在typescript中保存socket.io对象的更多数据,node.js,typescript,socket.io,typescript-typings,Node.js,Typescript,Socket.io,Typescript Typings,在不使用typescript时,我通常会执行类似于socket.username=username的操作。但现在我是,当我试图以同样的方式保存它时,它会给我错误 Property 'username' does not exist on type 'Socket' 我知道这意味着我需要扩展它,但我已经这样尝试过了 interface Socket { username: any } 但是没用我也试过了 interface SocketIO { username

在不使用typescript时,我通常会执行类似于
socket.username=username
的操作。但现在我是,当我试图以同样的方式保存它时,它会给我错误

Property 'username' does not exist on type 'Socket'
我知道这意味着我需要扩展它,但我已经这样尝试过了

interface Socket {
        username: any
}
但是没用我也试过了

interface SocketIO {
        username: any
}

没有运气。

只要
socket['username']=username
就可以了

如果您想要类型安全,并且想要对
username
属性进行自动完成,则可以扩展
Socket
接口

interface ExtendedSocket extends Socket {
  username: string;
}
然后,您可以将原始的
套接字
转换为自定义类型:

const mySocket = <ExtendedSocket>socket;
mySocket.username = 'user1'; // won't throw errors and autocomplete will work
constmysocket=socket;
mySocket.username='user1';//不会抛出错误,自动完成将起作用

这似乎接受一个
套接字。username=“John”

但更好的解决方案(IMHO)是将套接字接口扩展到您自己的套接字:

interface ExtSocket extends SocketIO.Socket 
{
  username: string;
}
然后将套接字本身声明为
socket:ExtSocket或使用丑陋的类型转换:

(套接字作为ExtSocket)。username=“John”

interface ExtSocket extends SocketIO.Socket 
{
  username: string;
}