使用函数接口确保参数但推断更具体的返回类型 [英] Use function interface to ensure parameters but infer more specific return type

查看:33
本文介绍了使用函数接口确保参数但推断更具体的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数签名,我需要一堆函数来遵循它,就像这样:

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.

不必在每个回调中指定两个参数的类型,我只想指定符合 ActionCallback 的变量,以便推断参数类型:

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

但是这样做意味着无法推断出通用参数,因此我必须明确指出返回类型或让它默认为 any

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

有没有办法最小化我必须显式标记的类型数量,确保函数返回一个 Promise 并从函数体推断出 Promise 的解析?

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?

推荐答案

由于函数可以在其参数中推断泛型类型,因此一个简单的环绕函数就可以获得这种行为:

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>

这篇关于使用函数接口确保参数但推断更具体的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆