I have a function with two generic types, In and Out:
function createTask<
In extends Record<string, any> = {},
Out extends Record<string, any>,
>(task : TaskFunction<In, Out>) : Task<In, Out>
type TaskFunction<In, Out> = (args : TaskWrapper<In>) => Out | Promise<Out>;
// TaskWrapper wraps several other types and interfaces, so args is more than just `In`
This code currently does not compile, because you cannot have a required generic type (Out) after an optional one (In).
How do I tell the Typescript compiler that I want to let the user of this function do one of three things:
Don't specify any generics:
createTask(...). The type ofInshould default to{}, andOutshould be inferred from the return value of theTaskFunction.Specify only
In:createTask<A>(...). As above,Outshould be inferred.Specify both
InandOut:createTask<A, B>(...).
Essentially I'm looking for a way to say "this generic is optional and should be inferred". I know there's an infer keyword but from the limited documentation I've found on it, it doesn't seem to support this use case.
I've also tried to assign a default value to Out, but then it always uses that default value instead of inferring from TaskFunction.
I can reverse the order of In and Out, but then Out always has to be specified even though it can easily be inferred, if the user wants to specify In.
I also prefer not to force users to add the default value {} every single time they call the function.
Is this at all possible to do with Typescript, or will I have to always require In to be specified?
Outas well?Out extends Record<string, any> = Record<string, any>Outit always uses the default instead of inferring. I updated my post to make this clearer.Outresolved as expected..