Assigning generics function to delegate in Typescript

余生颓废 提交于 2019-12-25 09:28:26

问题


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?


回答1:


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)



来源:https://stackoverflow.com/questions/40548715/assigning-generics-function-to-delegate-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!