sennett
sennett

Reputation: 8444

Curry generic function with Ramda and Typescript

I have a generic function:

function hello<T>(n: number, s: string, thing: T): Array<T> {
  return [thing]
}

const result = hello(1, 'string arg', 'generic arg')

result has type string[] which is expected.

However if I curry it:

function hello<T>(n: number, s: string, thing: T): Array<T> {
  return [thing]
}

const fun1 = curry(hello)(1, 'string arg')

const result = fun1('generic arg')

result now has type unknown[].

How can I curry a generic function in Ramda whilst maintaining the type? I'm using Ramda 0.27.1

Upvotes: 2

Views: 1345

Answers (2)

Sabbir Ahmed
Sabbir Ahmed

Reputation: 1704

As of ramda: "^0.29.1", I came up with the following solution:

function hello<T>(n: number, s: string, thing: T): Array<T> {
    return [thing];
}

const fun1 = R.curry(hello<string>)(1, "string arg");

const result = fun1("generic arg");

The trick is to pass the type parameter at the time of creating the curried function. After that, you should receive the correct output type (i.e. string[]).

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 192317

The signature of R.curry with 3 parameters is:

curry<T1, T2, T3, TResult>(fn: (a: T1, b: T2, c: T3) => TResult): CurriedFunction3<T1, T2, T3, TResult>;

As you can see, you'll need to manually type the curried function (codesandbox):

function hello<T>(n: number, s: string, thing: T): Array<T> {
  return [thing];
}

const fun1 = curry<number, string, string, string[]>(hello)(1, 'string arg');

const result = fun1('generic arg');

console.log(result);

Upvotes: 2

Related Questions