使用函数接口来确保参数但推断更具体的 return 类型

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

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

type ActionCallback<R = any> = (param1: SpecificType, param2: OtherType) => Promise<R>

基本上,参数的类型定义明确,它必须 return 一个承诺,但该承诺解决的问题取决于函数。

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

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

但是这样做意味着无法推断通用参数,所以我要么必须明确指出 return 类型,要么让它默认为 any

有没有一种方法可以最大限度地减少我必须显式标记的类型,确保函数 return 是一个 Promise 并从函数体中推断出 promise 的解析?

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

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>