TypeScript generics binding for function reference without lambda

Viewed 167

Is it possible to bind generics argument in TypeScript function reference?

For example, I have a Koa middleware with definition:

const genericsMiddleware: <T extends MyType>(ctx: MyRouterContext<T>) => Promise<any> = 
  <T extends MyType>(ctx: MyRouterContext<T>) => 
    Promise.resolve(ctx.body.value);

router.post('/api/endpoint', 
  someOtherMiddleware,
  genericsMiddleware); // How to bind to certain type?

router.post('/api/endpoint', 
  someOtherMiddleware,
  (ctx) => genericsMiddleware<TypeDef>(ctx)); // This works but lambda is useless

Now I use a lambda to wrap the function call to genericsMiddleware, but that is only because of I haven't figured out if it is possible to bind the generics type in a function reference.

I do use Ramda a lot too, and face the same problem with eg. R.flatten as I need to wrap it with lambda to have the types bound correctly, eg.

R.pipe(
  R.map(mappingFunction)
  (list) => R.flatten<string>(list)
)(data)

instead of

R.pipe(
  R.map(mappingFunction),
  R.flatten<string>
)(data)
1 Answers

This is possible in TypeScript 4.7:

interface Box<T> {
  value: T;
}

function makeBox<T>(value: T) {
  return { value };
}

const makeHammerBox = makeBox<Hammer>;
const makeWrenchBox = makeBox<Wrench>;
Related