typescript cannot infer the type coming from a callback function

Viewed 114

I define a function like this:

const func1 = <T, R>(x: T) => (f: (x: T) => R) => f(x)

Then call it like this:

func1(2 + 4)(a => a > 5)

I would expect the type of the result is boolean. but the type of func1 that typescript inferred is:

use<number, unknown>(x: number): (f: (x: number) => unknown) => unknown

How do I force typescript to recognize the type R?

2 Answers

You need to redefine it so func1() returns a generic function since you don't know what R is until a function is passed in.

const func2 = <T>(x: T) => <R>(f: (x: T) => R) => f(x)

The easiest way is to explicitly provide T and R, like so:

func1<number, boolean>(2 + 4)(a => a > 5)
Related