Home > Mobile >  Assign to generic function parameter in TypeScript
Assign to generic function parameter in TypeScript

Time:04-30

I would like to use a generic function as an parameter. However, I can't find how to instanciate such a type. Here's a simple example, that I would expect to work:

function foo(a: number, f: <U>(a: number) => U) {
    f(a) // removed the return to make the example simpler
}
function bar(a: number) : number {
    return 2*a
}
foo(8, bar);

Thing is, I get this error:

Argument of type '(a: number) => number' is not assignable to parameter of type '(a: number) => U'. Type 'number' is not assignable to type 'U'. 'U' could be instantiated with an arbitrary type which could be unrelated to 'number'.

The last part seems especially odd to me, since U shouldn't be anything other than a number in this case. How do I instanciate U as a number? Is there a specific syntax?

CodePudding user response:

I am not quite sure what you are trying to achieve here but moving U to the front will fix this problem:

function foo<U>(a: number, f: (a: number) => U) {
    return f(a) 
}
function bar(a: number) : number {
    return 2*a
}
foo(8, bar);

If you want to introduce generic types in a function declaration you should put them right after the function name. When the function is called TypeScript will then try to infer the correct types.

  • Related