Developing a game involving client/server communication, where different communication "Channels" with unique names and structures are utilized. To simplify the process of handling these channels and their expected parameters, I created an interface as follows:
export interface Channel {
name: string;
message_format: string;
}
This allows for defining channels in the following manner:
export const Channels = {
player_id: {
name: 'PID',
message_format: '{id}'
} as Channel,
join_request: {
name: 'JOIN',
message_format: '{roomId}:{username}',
} as Channel
};
Additional functions have been implemented to assist in creating and parsing requests:
export function createMessage(channel: Channel, args: { [key: string]: string }) {
let msg = channel.message_format;
for (let key in args) {
msg = msg.replace(`{${key}}`, `{${args[key]}}`);
}
return msg;
}
export function parseMessage(channel: Channel, msg: string) {
const args = {} as { [key: string]: string };
const regex = new RegExp(`{(.*?)}`, 'g');
let formatMatch;
const spl = msg.split(':');
let index = 0;
while ((formatMatch = regex.exec(channel.message_format)) !== null) {
args[formatMatch[1]] = spl[index++].replaceAll('{', '').replaceAll('}', '');
}
return args;
}
Presently, the Join Request Listener is structured like this:
function onJoinRequest(msg: { roomId: string, username: string }) {
console.log(msg);
}
To invoke the Listener, the following syntax must be used:
onJoinRequest(parseMessage(Channels.join_request, "{myRoomId}:{myUsername}") as { roomId: string, username: string });
An issue arises from having to define the contents of the Join Request multiple times:
In Channels, specifying the message format as
{roomId}:{username}
In the function declaration of
onJoinRequest
, outliningmsg
as{ roomId: string, username: string }
When calling
onJoinRequest
and asserting that the object returned byparseMessage()
adheres to the type
.{ roomId: string, username: string }
The desire is for Typescript to automatically determine the type of msg
within the listener based on the content of message_format
, eliminating the need to redundantly specify the message structure in different places.
Is there a method for Typescript to infer the type of msg
in the listener based on the defined message_format
?