Skip to content

ReturnType not being evaluated when used in function definition generics alias #41391

@carlos-algms

Description

@carlos-algms

Scenario:

Given an indexed object of functions that return different value types, generate a new object with the same indexes and the return value of the functions.

const given = {
  foo: () => 1,
  bar: () => 'milka',
};

const generatedResult = {
  foo: 1,
  bar: 'milka',
};

Failing example:

TypeScript is not re-evaluating the Types when calling the function with predictable values:
fail
It can predict the functions and their return types, but it is not evaluating ReturnType<...>

Workaround example:

The proper types are correctly inferred when using an anonymous type directly in the return type of the function:
pass

This workaround is not desired given the need for using the Type definition inside the body of the function.

TypeScript Version: 4.0.3

Search Terms:

  • ReturnType
  • Generics

Code

function extract<
  P extends string,
  M extends Record<P, () => any>,
  Ret extends {
    [K in P]: ReturnType<M[K]>;
  }
>(_map: M): Ret {
  return <Ret>{};
}

const { foo, bar } = extract({
  foo: () => 1,
  bar: () => 'bar',
});

Expected behavior:
Variable foo should be of type number
Variable bar should be of type string

Actual behavior:
All variables are of type any

Playground Link:
Playground Link or a CodeSandbox Link - Both with the same behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions