Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using generic type parameter as parameter

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);
}
like image 523
dstr Avatar asked May 30 '16 12:05

dstr


People also ask

Is generic type parameter?

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.

How do you provide a generic parameterized type?

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.

Which data type Cannot be parameterized?

3. Which of these data type cannot be type parameterized? Explanation: None.

How many type parameters can be used in a generic class?

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.


1 Answers

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.

like image 120
Luke Avatar answered Sep 22 '22 22:09

Luke