gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:55:42 24 4
gpt4 key购买 nike

在不使用 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)。

interface ExtendedSocket extends Socket {
username: string;
}

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

const mySocket = <ExtendedSocket>socket;
mySocket.username = 'user1'; // won't throw errors and autocomplete will work

关于node.js - 在 typescript 中保存 socket.io 对象的更多数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48058924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com