我创建了类似于socket.io文档中的提案的类型: https://socket.io/docs/v4/typescript/#custom-types-for-each-namespace
然后我使用自定义类型初始化 io 服务器:
private constructor(server: any) {
this.io = new Server<ClientToServerEvents, ServerToClientEvents, InterServerEvents, SocketData>(server, {
cors: {
origin: 'http://localhost:4200',
credentials: true
}
});
this.io.use(socketAthentication);
this.initializeSocketEvents();
logger.info('Socket server started');
}
SocketData 类型示例:
export interface SocketData {
appId: string;
moduleId: number;
msg: string;
}
但是 VS Code 或打字稿编译器中的智能不关心我的类型。例如,我可以添加未在 socketData 接口中定义的属性,而不会出现任何错误。当我输入socket.data时,我没有智慧。 我错过了什么吗?
this.io.on('connection', (socket) => {
socket.data.appId = 'TEST';
socket.data.test = 'OK';
}
几天前我自己修复了这个问题,这有点奇怪,但实际上你必须指定
this.io
的类型才能告诉 IntelliSense 你的服务器/套接字的实际类型。
这样做应该可以解决问题:
private constructor(server: any) {
this.io: Server<ClientToServerEvents, ServerToClientEvents, InterServerEvents, SocketData> = new Server<ClientToServerEvents, ServerToClientEvents, InterServerEvents, SocketData>(server, {
cors: {
origin: 'http://localhost:4200',
credentials: true
}
});
this.io.use(socketAthentication);
this.initializeSocketEvents();
logger.info('Socket server started');
}
打字稿似乎没有从模板化的 Socket.IO 服务器推断套接字,因此无法找到套接字的实际类型。 您可以将鼠标悬停在
socket
上进行检查。 VS Code 实际上并不显示模板化套接字,但实际上是默认套接字