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
{{ message }}
Repository navigation
Apply function generics as part of type definition #40542
constid=<T>(val: T)=>valtypeIdType=typeofid// type IdType = <T>(val: T) => TtypeRet=ReturnType<typeofid>// type Ret = unknown
It would be nice to be able to do something like so:
constid=<T>(val: T)=>valtypeIdType<T>=(typeofid)<T>// type IdType<T> = (val: T) => T// Or by extension:typeRet<T>=ReturnType<(typeofid)<T>>// type Ret<T> = T
Use Cases
This would be useful to use with the vriad/zod library, to implement different field validators depending on a parameter, like so:
// the dateSchema param could be a schema for an ISO 8601 string or a Date object, or even some custom date-like typeconstfooSchema=<T>(dateSchema: z.ZodSchema<T>)=>z.object({name: z.string(),date: dateSchema})typeFoo<T>=z.infer<ReturnType<(typeoffooSchema)<T>>>// expected result: type Foo<T> = { name: string, date: T }
Checklist
My suggestion meets these guidelines:
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, etc.)
I am understanding this proposal correctly that IdType here
const id = <T>(val: T) => val
type IdType = typeof id
would be type IdType<T> = (val:T) => T as opposed to type IdType = <T>(val:T) => T ? Or is idea here that you you should be able to qualify generic function type like type IdType = <T>(val:T) => T via <T> suffix e.g. type IdNum = IdType<number> // (val:number) => number ?
Activity
Gozala commentedon Jun 9, 2021
I am understanding this proposal correctly that
IdTypeherewould be
type IdType<T> = (val:T) => Tas opposed totype IdType = <T>(val:T) => T? Or is idea here that you you should be able to qualify generic function type liketype IdType = <T>(val:T) => Tvia<T>suffix e.g.type IdNum = IdType<number> // (val:number) => number?jmacmahon commentedon Jun 29, 2021
I meant the latter, so like you say,
type IdNum = IdType<number> // (val:number) => number.I think the former would be incorrect, because the parameter
Tis not present when declaringtype IdType.ahejlsberg commentedon Jan 27, 2022
This feature is now implemented in #47607.