Use function interface to ensure parameters but infer more specific return type

可紊 提交于 2021-01-29 06:13:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!