Skip to content

Improve inference of return types of generic functions.Β #62018

Closed as not planned
@royavidan

Description

@royavidan

πŸ” Search Terms

"generic","lambda","function","infer"

βœ… Viability Checklist

⭐ Suggestion

I want that using infer on a generic function type will know to identify the type parameter better, instead of using unknown.

πŸ“ƒ Motivating Example

Let's say I want to create a type called TupleConverter that will have 2 type parameters, a tuple and a function that converts each element.
`type TupleConverter<A extends readonly any[], FN extends (obj: U) => any> = ...

In the type itself, even like that, I wouldn't expect to be able to use FN as a generic type (use FN<number> for example), so I would try to extract the type FN will return for each parmeter with infer: type TupleConverter<A extends readonly any[], FN extends (obj: any) => any> = A extends [infer F, ...infer R] ? (
[FN extends (obj: F) => infer T ? T : never, ...TupleConverter<R, FN>]
) : never.

The problem is that, while in compile time when TypeScript will evaluate this line, even though it will know the type I would still get unknown for T.

For a simpler example: Let's say I have this function:
const f = <T>(obj: T) => ([obj])

If I use the function itself, I can get the return type of f with number as type using f<number>. But in typing, I cannot get the type in any way from the type of f.

My suggestion is that an expression like typeof f extends (obj: number) => infer R ? R : never will return number[] instead of unknown[].

πŸ’» Use Cases

  1. What do you want to use this for? To use generic functions to translate types (mostly tuples and objects) instead of creating a brand new type for each translation.
  2. What shortcomings exist with current approaches? I can use the function itself with type parameter, but cannot use its type.
  3. What workarounds are you using in the meantime? For typing, none.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions