问题
我正在使用socket.io-client和tyscript。
创建套接字实例时,我会在套接字选项的身份验证中设置一个令牌属性,但是使用时会发生类型错误。
我该如何解决?
- “ socket.io-client”:“ 4.5.0”
- “ typescript”:“ 4.6.4”
源
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);
});
错误
ts2339:属性'token'在type'{[key:string]:any; } | ((cb :(数据:对象)=&gt; void)=&gt; void)'。
属性“令牌”不存在于类型上'(cb :( data:object)=&gt; void)=&gt; void'。
的定义
export interface SocketOptions {
/**
* the authentication payload sent when connecting to the Namespace
*/
auth: {
[key: string]: any;
} | ((cb: (data: object) => void) => void);
}
插座选项参考文献文档
socket.on('created', () => {
const tmp: any = socket.auth;
console.log("token", tmp.token);
});
让我告诉你,我说的英语不能很好。
对不起,如果这是一个奇怪的句子。
请指出您不理解的任何句子,我将尽力纠正它们。
如果您能回答,我会很感激。
谢谢。
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);
});
source capture
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
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.
发布评论