Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: How to Specify Arrow Function Type's Generic Parameter

When we declare the type of an arrow function with generic parameters, we can do the following:

interface ArrowFunc {
    <T>(arg: T): T;
}
type ArrowFunc2 = <T>(arg: T): T;

Now I need to use this type with the generic parameter specified, how may I achieve this? Obviously type Func = ArrowFunc<T> doesn't work, since the generic parameter belongs to the function instead of the type.

like image 425
true_mogician Avatar asked Aug 01 '26 08:08

true_mogician


1 Answers

We can do this with a workaround. When we declare a variable of type ArrowFunc, we can use an instantiation expression where we replace T with a type of our choice.

interface ArrowFunc {
    <T>(arg: T): T;
}

declare const fn: ArrowFunc

type Func = typeof fn<number>
// type Func = (arg: number) => number

Playground

like image 80
Tobias S. Avatar answered Aug 02 '26 22:08

Tobias S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!