LudvigH
LudvigH

Reputation: 4736

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. Recursion seems to me as a good suggestion.

My attempt in vanilla ES is below.

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. The separate definition of "ret" is to allow proper inference of return type.

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;
};

Upvotes: 0

Views: 1940

Answers (1)

arpl
arpl

Reputation: 3633

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;
};

Upvotes: 5

Related Questions