使用泛型类型参数作为参数 [英] Using generic type parameter as parameter
问题描述
我正在尝试创建一个通用函数,该函数使用 any
类型参数调用另一个函数.这是我试过的:
I'm trying to create a generic function which calls another function with an any
type parameter. This is what I tried:
static GetInstance<T>(): T {
return <T>injector.get(T); // get(param: any): any
}
问题是这不能编译.我收到 Cannot find name 'T'
错误.
The problem is this doesn't compile. I'm getting Cannot find name 'T'
error.
我尝试了 get(typeof T)
但 typeof T 是字符串 "function"
.
I tried get(typeof T)
but typeof T is string "function"
.
我能做什么?
澄清:get() 方法接受类型.例如,您可以像这样使用它:
For clarification: get() method accept types. For example you can use it like this:
import { MyService } from '..'
constructor(){
let val = this.injector.get(MyService);
}
推荐答案
Typescript 中的泛型仅在设计时使用.在某些 JS 替换中永远不会出现 comiled.但是您想要做的实际上是使用泛型,期望它们在 javscript 中编译.
Generics in Typescript are design time only. There will never be comiled in some JS replacement. But what you are trying to do, is actually use the generics expecting them to be compiled in javscript.
换句话说,T
不存在.它只为你增强.您不能将其作为变量传递,因为它不是变量.正如我所说,这完全是想象中的.
In other words, T
does not exist. it´s only augmented for you. You cannot pass it as a variable, as it is no variable. As I said, it is completely imaginary.
因此 GetInstance
方法必须使用实际值调用 get
函数,而不是 T
,因为它不存在.
So the GetInstance
method must call the get
function with an actual value, and not T
as it does not exist.
这篇关于使用泛型类型参数作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!