javascript - 如何使用参数转发注释高阶函数
问题描述
我正在尝试注释这个组合:
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 的答案感兴趣,因为这对我来说是一个很好的迁移点。
解决方案
这是您可以在此示例中使用的一种方法:
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 的新手,这个例子依赖于Generics和Rest Parameters。具体来说,此示例中的 Rest 泛型是在3.0中添加的。
推荐阅读
- apache-kafka - kafka堆内存大小取决于哪些因素?
- r - here::here() 可以用来加载 .Rdata 文件吗?
- java - 打印出特定数量的排列(java)
- javascript - 带有 Javascript/Css3 实践的模态图像
- python - GPIO输入激活tkinter中的按钮
- java - Java“有序”信号量
- python - pygame,视频未初始化且未找到视频 - 在 Windows 10 中使用 ubuntu 终端
- java - 带有apache poi的excel上的多组列
- excel - 如何将 VBA 代码限制为特定的工作表?
- javascript - 我想添加具有某些hrefs的某个onclick功能