My goal is to extract the Parameter
types of a generic typed function into a new generic type which I can use later:
// we have a given function like this:
function genericFunction<T>(a: T) {
return a;
}
type genericParamsType = Parameters<typeof genericFunction>; // this will resolve to a type of [unknown]
// I would like to achieve something like this:
// type genericParamsType<PassDownType> = Parameters<typeof genericFunction<PassDownType>>;
// but that is a syntax error
// if it would work, I could the following:
// const newparams: genericParamsType<string> = ["hello"] // correct
// const newparams2: genericParamsType<number> = ["hello"] // error because its not a string
TypeScript 4.7 introduced instantiation expressions , so your original idea is no longer a syntax error. Instantiation expressions allow generic functions to be, well, instantiated with concrete types for generic type parameters.
Thus, genericParamsType
can be written as follows:
type genericParamsType<T> = Parameters<typeof genericFunction<T>>;
While this still does not allow for a truly general solution as one still has to use the typeof
type query on a concrete implementation, it is sufficient to cover the use case outlined in the question:
// we have a given function like this:
function genericFunction<T>(a: T) {
return a;
}
type genericParamsType<T> = Parameters<typeof genericFunction<T>>;
const newparams: genericParamsType<string> = ["hello"] // OK
const newparams2: genericParamsType<number> = ["hello"] // Type 'string' is not assignable to type 'number'.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.