Is there a way to set the return type of the function to depend on the type of a local variable?
I have a set of validation methods:
validateA(things: Thing[]): { badA: string[], badB: number[] }
validateB(things: Thing[]): { anotherBadA: string[], anotherBadB: number[] }
And then I have a wrapper meant to just essentially run all of them and merge their results:
validateAllTheThings(things: Thing[]) {
const problems = {
...this.validateA(things),
...this.validateB(things),
};
return problems;
}
So, validateAllTheThings
should have the return type that’s the same as the type of problems
, which is all the returned objects merged together.
The cleanest way I’ve found it to use ReturnType
:
function validateAllTheThings(things: Thing[]): ReturnType<WrapperClass['validateA']> & ReturnType<WrapperClass['validateB']> {
But this is super verbose, and won’t scale well. It would be nice if I could just tie the function’s return type to inferred type of problems
.