简体   繁体   中英

Assign to generic function parameter in TypeScript

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM