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
}
The problem is this doesn't compile. I'm getting Cannot find name 'T'
error.
I tried get(typeof T)
but typeof T is string "function"
.
What can I do?
For clarification: get() method accept types. For example you can use it like this:
import { MyService } from '..'
constructor(){
let val = this.injector.get(MyService);
}
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.
In order to use a generic type we must provide one type argument per type parameter that was declared for the generic type. The type argument list is a comma separated list that is delimited by angle brackets and follows the type name. The result is a so-called parameterized type.
3. Which of these data type cannot be type parameterized? Explanation: None.
Multiple parameters You can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.
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.
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.
So the GetInstance
method must call the get
function with an actual value, and not T
as it does not exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With