Jørgen Tvedt Jørgen Tvedt - 23 days ago 10
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

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)

Comments