首页 > 解决方案 > 如何使用参数转发注释高阶函数

问题描述

我正在尝试注释这个组合:

const get1 = (n: number, s: string) => `${n}_${s}`;
const get2 = (s: string, n: number) => `${n}_${s}`;

const foo = (get) => (...args) => {
    get(...args);
}

const foo1= foo(get1);
const foo2= foo(get2);


foo1(2, 'qwe');
foo2('qwe', 1)

目前我正在使用 Flow 作为类型检查器,但我也对 TypeScript 的答案感兴趣,因为这对我来说是一个很好的迁移点。

标签: javascripttypescripttypesflowtype

解决方案


这是您可以在此示例中使用的一种方法:

const get1 = (n: number, s: string) => `${n}_${s}`;
const get2 = (s: string, n: number) => `${n}_${s}`;

const foo = <T extends any[], R>(get: (...args: T) => R) => (...args: T): R => {
  return get(...args);
};

const foo1 = foo(get1);
const foo2 = foo(get2);

foo1(2, "qwe");
foo2("qwe", 1);

打字稿游乐场

如果你是 TypeScript 的新手,这个例子依赖于GenericsRest Parameters。具体来说,此示例中的 Rest 泛型是在3.0中添加的。


推荐阅读