• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: How to properly extract generic parameters of function in Typescript

Resolved: How to properly extract generic parameters of function in Typescript

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

Usually I use Typescript’s Parameters to receive all parameters required by a function of a class:
It works just fine with predefined types in function signature like this: get(id: number).
I’m currently trying to get parameters of function that has the following signature:
But with the Parameters it supposes that the T is never and I can’t pass my own T into the parameters of such arrow function to get something like Parameters<Controller["get"]<T>> to get proper generic when I call my function like in the beginning.
Edit 1: Minimal Reproducible Example
Example 1 Example 2

Answer:

TypeScript 4.7 introduced instantiation expressions as implemented in microsoft/TypeScript#47606, so if you have a value f of a generic function type, you can specify the type parameters of that function without calling it. Let’s say your function declaration is
Then you can instantiate T and U with, say, number and string, to get a new expression:
You can even use the typeof type operator to get the type of such a expression without actually creating one:
Unfortunately, you can’t do this purely at the type level (see this comment on ms/TS#47606). You need that variable f, or a property of a variable. If you only have the type of f, then you can’t instantiate its type parameters
Luckily, inside of Test, you do have a value of the generic function type you care about. It’s this.genericFunction or this.genericFunctionPromise:
And that actually works… except that there are errors on this in TypeScript 4.7. Ugh. This turns out to be a bug in TypeScript, see microsoft/TypeScript#49451. This bug has been fixed at microsoft/TypeScript#49521, so typescript@next nightly build will work, and it will be released with TypeScript 4.8.
If you need to get this working in TS4.7, you could declare a fake variable of type Test and use it instead, since we just care about types:
Playground link to code

If you have better answer, please add a comment about this, thank you!

typescript
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Why reference in pointer array doesn’t have data?

24/03/2023

Resolved: EntityFramework creates/runs migrations using parameterless DataContext instance

24/03/2023

Resolved: Visual Studio 2022 crashes when using breakpoints

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.