Home > Back-end >  typescript function that returns ReturnType of callback
typescript function that returns ReturnType of callback

Time:03-17

How can I annotate a function that takes a callback, and have such function return type inferred from the callback return type?

// say that callback takes a number
function takesCallback(cb: (arg:number) => infer T /* error */ ) {
  return cb(42)
}

takesCallback(x => 'foo') // should infer 'string' 

CodePudding user response:

Here you can use the helper ReturnType, also it is necessary to rewrite the generic structure so that it can be constrained to a function

function takesCallback<T extends (...args: unknown[]) => unknown>(callback: T): ReturnType<T> {
  return callback(42) as ReturnType<T>;
}

const res1 = takesCallback(x => 'foo'); // string
const res2 = takesCallback(x => 123);   // number

Playground

  • Related