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

Time:11-09

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.

CodePudding user response:

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

  • Related