I am trying to infer the type, but it simply doesn’t work. I tried asking A.I and they suggest me the same not working solution
This is the simple class with the action and the merging function itself
import { Server } from "socket.io";
export default class SocketAction<T = any> {
// public name: string;
public action: Function;
constructor(public name: string, action: (socket: Server, data: T) => Promise<any>) {
this.action = action;
}
}
// create type from SocketAction for merged object with key as the values of the SocketAction name property and keep intellisense
export type SocketActionMap<T extends SocketAction[]> = {
[K in T[number] as K["name"]]: K;
};
export function createSocketActionMap(io: Server, ...actions: SocketAction[]) {
return actions.reduce((acc, action) => {
action.action = action.action.bind(null, io);
acc[action.name] = action;
return acc;
}, {} as SocketActionMap<typeof actions>);
}
and this is how I use it, but I don’t get intellisense on the object suggesting SocketAction name property
import type { Server as HttpsServer } from "https";
import { Server } from "socket.io";
import SocketAction, { createSocketActionMap } from "./libs/socket/action.c";
// import { connectAction } from "./libs/socket/connect";
import logger from "./utils/logger";
export default function (httpsServer: HttpsServer) {
const io = new Server(httpsServer, {
cors: {
origin: [
....,
],
methods: ["GET", "POST"],
},
});
const handleErrors = (err: unknown) => {
logger.error("Socket error: ", err);
};
const connectAction = new SocketAction("connection", async (socket: Server, data: any) => {
console.log("connection action: ", data);
});
const debugAction = new SocketAction("debug", async (socket: Server, data: any) => {
console.log("debug action: ", data);
});
// this is the merged object
const sc = createSocketActionMap(io, connectAction);
io.on("connection", (socket) => {
console.log("Socket connected: ", socket.id);
// sc.login.action({ test: "test" });
socket.on("disconnect", () => {
console.log("Socket disconnected: ", socket.id);
});
socket.on("system-message", (data: TSystemMessagePayload, options, cb) => {
if (!sc[data.action]) {
console.error(`Unknown action: ${data.action}`);
return;
}
sc[data.action].action(data);
cb("calling the callback. We are done!");
// console.log("payload: ", data);
});
socket.on("connect_error", (err) => handleErrors(err));
socket.on("connect_failed", (err) => handleErrors(err));
});
return io;
}
This is my code right now. It is working but I do not get intellisense.
I appreciate any help. Thank you