[英]Why is a type of generic function not generic itself?
考虑以下示例代码:
interface so<T>
{
a: T;
}
type test = <T>() => so<T>;
const so: test<number> = undefined;
哪个失败
类型“ test”不是通用的
请解释。
首先,这有点令人困惑,泛型基本上可以通过两种方式来使用函数签名。 它可以是作为函数的泛型类型,也可以是非泛型但代表泛型函数的类型。
例如:
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
在第一种情况下( GenericTypeThatIsAFunction
),您必须在声明站点指定type参数,并将其永久固定到引用。 对引用的调用只能针对事先指定的类型进行。
在第二种情况( TypeThatIsAGenericFunction
)中,除了在调用站点(否则会推断出)之外,您无需指定type参数。 实现必须处理T
任何可能值。
从通用函数签名创建非通用函数签名可能会很有用,但目前尚无语法可以支持此功能。 有一些讨论允许这种行为,但是我无法说出它是针对近期最佳计划的(声明者:不是编译器团队的成员,除了公共信息之外,我对他们的计划没有任何见识)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.