2016-11-11 71 views
0

委托我不能得到这个简单的代码片段在打字稿编译(1.8)分配泛型函数打字稿

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

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

我有一个函数,它接受一个委托,但泛型函数转换成代表格式要求我执行这个额外的步骤:

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

......这对我来说似乎并不理想。任何想法,为什么这不起作用,或者如果有另一种语法来实现相同?

回答

1

你不需要通用约束可言,这将做到:

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

code in playground

编译器推断通用约束是基于您明确定义的类型数量变量。
另一种方式来做到这一点是:

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

code in playground

+0

你是对的!在这种情况下,我仍然觉得你不能使用类型约束有些尴尬。 –

+0

好吧,编译器不喜欢'let a = test '的语法,只有在调用函数时才应该使用泛型约束。 –