1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.