简体   繁体   English

为什么一种泛型函数不是泛型本身?

[英]Why is a type of generic function not generic itself?

Consider the following example code: 考虑以下示例代码:

interface so<T>
{
    a: T;
}

type test = <T>() => so<T>;

const so: test<number> = undefined;

Which fails with 哪个失败

Type 'test' is not a generic 类型“ test”不是通用的

Explain please. 请解释。

This is a bit confusing at first, there are basically two ways a function signature can be involved with generics. 首先,这有点令人困惑,泛型基本上可以通过两种方式来使用函数签名。 It can either be in a generic type that is a function or if can be in a type that is not generic but that represents a generic function. 它可以是作为函数的泛型类型,也可以是非泛型但代表泛型函数的类型。

Ex: 例如:

type GenericTypeThatIsAFunction<T> = (o: T) => void
let functionThatIsNotGeneric: GenericTypeThatIsAFunction<number> // the generic type parameter is fixed
functionThatIsNotGeneric = (o: number) => { } // no generics here 
functionThatIsNotGeneric(1) // No generic here 


type TypeThatIsAGenericFunction = <T>(o: T) => void
let genericFunction: TypeThatIsAGenericFunction // the generic type is NOT fixed
genericFunction = <T>(o: T) => { } //  the implementation has to deal with any posible T
genericFunction(1) // T is not fixed to number for just this call 

In the first case ( GenericTypeThatIsAFunction ) you must specify the type parameter at declaration site and it is permanently fixed to the reference. 在第一种情况下( GenericTypeThatIsAFunction ),您必须在声明站点指定type参数,并将其永久固定到引用。 The calls to the reference can only happen for the type specified beforehand. 对引用的调用只能针对事先指定的类型进行。

In the second case ( TypeThatIsAGenericFunction ) you don't specify the type parameter except at call site (or it gets inferred). 在第二种情况( TypeThatIsAGenericFunction )中,除了在调用站点(否则会推断出)之外,您无需指定type参数。 The implementation has to deal with any possible value for T . 实现必须处理T任何可能值。

While it might be useful to create a nongeneric function signature from a generic function signature, there is currently no syntax to support this. 从通用函数签名创建非通用函数签名可能会很有用,但目前尚无语法可以支持此功能。 There are some discussions to allow this behavior but none are planed for the near future best I can tell (declaimer: not a member of compiler team I have no insight into their planning except for public info) 有一些讨论允许这种行为,但是我无法说出它是针对近期最佳计划的(声明者:不是编译器团队的成员,除了公共信息之外,我对他们的计划没有任何见识)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM