问题
I have a function signature that I need a bunch of functions to follow which is something like this:
type ActionCallback<R = any> = (param1: SpecificType, param2: OtherType) => Promise<R>
Basically the types for the parameters are well defined and it must return a promise but what that promise resolves to is up to the function.
Instead of having to specify the type of both arguments in every callback I'd like to just specify the variable conforms to ActionCallback
so the parameters types are inferred:
const callback1: ActionCallback = async (a,b) => ({state: b().form, stuff: a});
const callback2: ActionCallback = async e => e.name; // doesn't need second arg in some cases
However doing it like this means the generic argument can't be inferred so I either have to explicitly indicate the return type or let it default to any
Is there a way to minimize how much types I have to explicitly mark, ensure the function returns a Promise and infer the resolve of promise from function body?
回答1:
Since functions can infer generic type in their arguments a simple function to wrap around can get this behaviour:
function MakeCallback<R>(callback: ActionCallback<R>): ActionCallback<R> {
return callback;
}
const callback1 = MakeCallback(async e => e.name); // now can infer the return as Promise<typeof e.name>
来源:https://stackoverflow.com/questions/55056008/use-function-interface-to-ensure-parameters-but-infer-more-specific-return-type