[英]Type annotatinig generic arrow function in typescript?
I want to code a typescript function that repeats a function n times to an argument, in a functional way. 我想编写一个以函数方式对一个参数重复n次的打字稿函数。 Recursion seems to me as a good suggestion.
在我看来,递归是一个很好的建议。
My attempt in vanilla ES is below. 我对香草ES的尝试如下。
const repeat = f => times => arg => {
if(times <= 0) {
return arg;
} else {
const val = repeat(f)(times-1)(f(arg))
return val;
}
}
My best attempt in annontating the type does not pass compilation. 我对类型的最佳尝试未通过编译。
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;
}
}
EDIT Following the advice of @arpl, but not writing a separate Interface, I settled for below. 编辑按照@arpl的建议,但没有编写单独的接口,我在下面解决了。 The separate definition of "ret" is to allow proper inference of return type.
“ 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;
};
Here is one way that uses an interface. 这是使用接口的一种方法。
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.