11

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);
}
3
  • 1
    You can't use a type as a value. If you need to pass in the type, you should do: get<T>() Commented May 30, 2016 at 12:32
  • 1
    I'm not sure that get() method accept types: what you are passing it is not a Typescript interface but a Typescript class which compiles to an object. Commented May 30, 2016 at 12:41
  • @pietro909: when you think that classes are actually functions, you can say that get() accepts functions as parameter. get() looks up key value in a dictionary collection with the supplied type as parameter. Commented May 30, 2016 at 13:11

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.