Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why return type is not inferred?

The generic return type R should be inferred as string, but it’s instead unknown. Why and how to make it to be inferred correctly?

function call<Args extends any[], R, F extends ((...args: Args) => R)>(
  fn: F, ...args: Args
): R {
  return fn(...args)
}

function some<T>(a: T[]): string { return "" }

let v = call(some, [1]) // => inferred type of v is unknown

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Use ReturnType<F> as the return type of your function to infer the type from the passed function instead of using the R generic

function call<Args extends any[], F extends ((...args: Args) => any)>(
  fn: F, ...args: Args
): ReturnType<F> {
  return fn(...args)
}

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading