Using generic type parameter as parameter

南楼画角 提交于 2021-02-20 19:08:20

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/37525618/using-generic-type-parameter-as-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!