Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get parameter types of a generic function with instantiated generic type parameters?

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

Playground

like image 215
josias Avatar asked Sep 06 '25 04:09

josias


1 Answers

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'.

Playground

like image 99
Oleg Valter is with Ukraine Avatar answered Sep 09 '25 00:09

Oleg Valter is with Ukraine