'How to define types of the auth properties in socket.io-client
Question
I am using socket.io-client with typescript.
When creating a socket instance, I set a token property in the auth of the Socket options, but an type error occurs when using it.
How can I resolve this?
- "socket.io-client": "4.5.0"
- "typescript": "4.6.4"
source
import { io, Socket } from "socket.io-client";
import { ServerToClientEventsInterface, ClientToServerEventsInterface } from "../../../backend/socket/interface/socketEventsInterface";
const socket: Socket<ServerToClientEventsInterface, ClientToServerEventsInterface> = io({
auth: (cb: any) => {
cb({ token: localStorage.token })
}
});
socket.on('created', () => {
console.log("token", socket.auth.token);
});
error
TS2339: Property 'token' does not exist on type '{ [key: string]: any; } | ((cb: (data: object) => void) => void)'. Property 'token' does not exist on type '(cb: (data: object) => void) => void'.
the definition of Socket options
export interface SocketOptions {
/**
* the authentication payload sent when connecting to the Namespace
*/
auth: {
[key: string]: any;
} | ((cb: (data: object) => void) => void);
}
Reference document
- https://socket.io/docs/v4/client-options/#socket-options
- https://socket.io/docs/v4/middlewares/#sending-credentials
tried
I've confirmed that the error can be avoided by the following method, but I don't think it's the right way to go.
socket.on('created', () => {
const tmp: any = socket.auth;
console.log("token", tmp.token);
});
let me tell you that I can't speak English well. I'm sorry if it's a strange sentence. Please point out any sentences that you do not understand, and I will do my best to correct them.
I would be very grateful if you could answer. Thank you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|