In the development of my project, I am creating a type system centered around commands and their corresponding results. My main objective is to build commands and eventually serialize them into JSON for transmission over the network. Since there will be numerous commands each requiring different fields, I am trying to avoid creating multiple sendCommandXXX()
functions. Instead, I aim to have a single generic function that can handle any command seamlessly. Here is what I have implemented so far:
// defining the basic structure required for all commands
interface CommandBase {
name: string;
}
// sample commands
interface CommandAddFile extends CommandBase {
name: 'AddFile';
filename: string;
contents: string;
}
interface CommandDeleteFile extends CommandBase {
name: 'DeleteFile';
filename: string;
}
interface CommandRefreshResults extends CommandBase {
name: 'RefreshResults'
}
// structure for command result
interface CommandResult {
success: boolean;
error?: string;
}
async sendCommand<T>(opts: T): Promise<CommandResult> {
// ... transmitting `opts` over the network
}
sendCommand<CommandAddFile>({
name: 'AddFile',
filename: 'test.txt',
contents: 'test'
}).then(res => {
console.log(res.success);
});
Currently, it seems repetitive to call sendCommand with both a specific command type in the template field and specifying the name
, which would typically remain the same. How can I streamline this process?