分配泛型函数以在Typescript中进行委托 [英] Assigning generics function to delegate in Typescript

查看:110
本文介绍了分配泛型函数以在Typescript中进行委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在Typescript(1.8)中编译此简单代码段

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?

推荐答案

您不需要

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

操场上的代码

编译器会根据您为变量明确定义的类型将通用约束推断为数字。

另一种方法是:

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;

操场上的代码

这篇关于分配泛型函数以在Typescript中进行委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆