A
A
Alexandroppolus2021-08-30 19:08:42
typescript
Alexandroppolus, 2021-08-30 19:08:42

How to convince the typescript that unknown is possible in ReturnType?

Hello.
Oil painting (and cheese):

function call<F extends () => unknown>(f: F): ReturnType<F> {
  return f()
}

It would seem, what is the problem? But alas, "TS2322: Type 'unknown' is not assignable to type 'ReturnType '" on the return line.

If you replace unknown with any other type, it also swears. And only the ungodly any , as well as the useless never in this situation, return without errors.

It looks like ReturnType forgets that it's actually the return value for f. What is he?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2021-08-30
@bingo347

TypeScript has a number of problems with functional types in generics due to their variance
. Here is how the result will be similar, but works without problems:

function call<R>(f: () => R): R {
  return f()
}

A
Alex, 2021-08-30
@Kozack

The first thing that came to mind:
return f() as ReturnType<F>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question