dstr
dstr

Reputation: 8938

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);
}

Upvotes: 10

Views: 9981

Answers (1)

Luke
Luke

Reputation: 8407

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.

Upvotes: 7

Related Questions