Jørgen Tvedt Jørgen Tvedt - 1 year ago 79
TypeScript Question

Assigning generics function to delegate in Typescript

I can't get this simple code snippet to compile in Typescript (1.8)

function test<T>(a: string, input: T): T {
return input

const xyz: (a: string, b: number) => number = test<number>

I have a function that takes a delegate, but converting the generics function into that delegate format requires me to perform this extra step:

const xyz: (a: string, b: number) => number = (a,b) => test<number>(a,b)

... which does not seem ideal to me. Any ideas why this does not work, or if there is another syntax to accomplish the same?

Answer Source

You don't need the generic constraint at all, this will do:

const xyz: (a: string, b: number) => number = test;

(code in playground)

The compiler infers the generic constraint to be number based on the type you explicitly defined for the variable.
Another way to do it is:

const xyz = test as (a: string, b: number) => number;

(code in playground)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download