Description
π Search Terms
"generic","lambda","function","infer"
β Viability Checklist
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
β 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
- 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.
- What shortcomings exist with current approaches? I can use the function itself with type parameter, but cannot use its type.
- What workarounds are you using in the meantime? For typing, none.