[SOLVED] typescript function that returns ReturnType of callback

Issue

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' 

Solution

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

Answered By – Daniel Rodríguez Meza

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *