I have a set of 4 different classes:
class AddCommand {
// TODO
}
class AddCommandOutput {
// TODO
}
class RemoveCommand {
// TODO
}
class RemoveCommandOutput {
// TODO
}
I am currently working on creating a function that can take either AddCommand
or RemoveCommand
as an argument, and then return the corresponding AddCommandOutput
or RemoveCommandOutput
based on the input.
Initially, my function looked something like this:
function processCommand(command: AddCommand|RemoveCommand): AddCommandOutput|RemoveCommandOutput {
// TODO:
}
However, I found myself needing to check the type of the return value after calling the function like this:
const result = processCommand(command);
if (result instanceof AddCommandOutput) {
} else {
// RemoveCommandOutput
}
To enhance the intelligence of the function, I could potentially modify it to look like this:
function processCommand<T>(command: AddCommand|RemoveCommand): T {
// TODO:
}
But even in this case, I would still have to specify the return type explicitly like so:
const result = processCommand<RemoveCommandOutput>(command);
Is there a way to further improve the function's intelligence by dynamically adjusting the return type based on the provided argument?
For example:
const result = processCommand(addCommand); // providing an instance of AddCommand so that the return type is AddCommandOutput
// With this, I should be able to access all the functions of AddCommandOutput