[英]Type annotatinig generic arrow function in typescript?
我想编写一个以函数方式对一个参数重复n次的打字稿函数。 在我看来,递归是一个很好的建议。
我对香草ES的尝试如下。
const repeat = f => times => arg => {
if(times <= 0) {
return arg;
} else {
const val = repeat(f)(times-1)(f(arg))
return val;
}
}
我对类型的最佳尝试未通过编译。
const repeat = <T>(f: T=>T) => (times: number) => (arg: T) => {
if(times <= 0) {
return arg;
} else {
const val: T = repeat(f)(times-1)(f(arg))
return val;
}
}
编辑按照@arpl的建议,但没有编写单独的接口,我在下面解决了。 “ ret”的单独定义是为了允许正确推断返回类型。
const repeat = <T>(f: (a: T)=>T) => (t: number) => (a: T) => {
const ret: T = t > 0 ? repeat(f)(t - 1)(f(a)) : a;
return ret;
};
这是使用接口的一种方法。
interface Repeat {
<T>(f: (a: T) => T): (t: number) => (a: T) => T;
}
const repeat: Repeat = f => t => a => {
return t > 0 ? repeat(f)(t - 1)(f(a)) : a;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.