You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Most of the time Typescript does a great job inferring types so its possible to write a higher-order function with generic types representing the inputs and outputs a function. For example:
// Infers the inputs and outputs of a functionfunctionf<X,Y>(fn: (x: X)=>Y): (x: X)=>Y{returnfn}functiong(x: number): string{returnx.toString()}// result has type (x: number) => string as we'd expectconstresult=f(g)
However, sometimes Typescript does not infer types well, such as #18807. In cases such as this, how are we supposed to explicitly define the generics of the function f?
The obvious example is f<number, string>(g) but that can be very tedious, especially the input type definition for g isn't defined separately and exported or if the output type of g is inferred.
A solution to this problem would be some way of destructuring the type of a function so I can pass typeof g as the generic argument to f like the following:
With conditional types you should be able to extract these types from the function, and no need for special destructuring operations.. e.g.:
f<ParamType<typeofg>,ReturnType<typeofg>>(g);typeParamType<T>=Textends(a: infer A)=>any ? A : never;typeReturnType<Textends(...args: any[])=>any>=Textends(...args: any[])=> infer R ? R : any;
mhegazy
added
the
Declined
The issue was declined as something which matches the TypeScript vision
label
Jul 17, 2018
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.
TypeScript Version: 2.5.2
Code
Most of the time Typescript does a great job inferring types so its possible to write a higher-order function with generic types representing the inputs and outputs a function. For example:
However, sometimes Typescript does not infer types well, such as #18807. In cases such as this, how are we supposed to explicitly define the generics of the function
f
?The obvious example is
f<number, string>(g)
but that can be very tedious, especially the input type definition forg
isn't defined separately and exported or if the output type ofg
is inferred.A solution to this problem would be some way of destructuring the type of a function so I can pass
typeof g
as the generic argument tof
like the following:The text was updated successfully, but these errors were encountered: