'Why using generic type be considered as using as value in generic class?

Why compiler complains the following codes T' only refers to a type, but is being used as a value here:

class Factory<T> {
    create(TCreator: (new () => T)): T {
         return new TCreator();
    }

    test(json: string) {
        // compile error here:
        //          T' only refers to a type, but
        //          is being used as a value here
        let a: T = this.create(T);

        ...
    }
}

I don't know.. Shouldn't T be a generic type in the class Factory? And can T be used as the argument of function "create" which has a parameter type as the same as T's constructor type.


I think what I want to do is to create an instance of T in the class Factory. I have tried like let a2: T = new T(); but ran into the same compile error.



Solution 1:[1]

For some reason, when used with a generic type within a class, you need to do it like this:

class Factory<T> {
  constructor(private TCreator: new () => T) {}

  test() {
    const t: T = new this.TCreator();
  }
}

It's not intuitive but it works. Any other way I tried, I ran into the same TS2693 error.

However, when outside of a class, the approach with a create function (as used in the question) works, as outlined in the TypeScript handbook.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zbr