Create a new object with the type received by parameter

Asked

Viewed 289 times

1

I have the following generic class:

class Generic<T> {

}

How do I create an object with received type? Something like this:

class Generic<T> {
    item: T = new T(); // isso é um exemplo, somente pra ilustrar o que preciso.
}
  • 1

    I don’t think that kind of approach is possible. Typescript is just a wrapper for Javascript, which offers some build-time features. What you are trying to do is something that would have to be checked at runtime, when Typescript no longer exists, and there is no longer any reference to the generic type received in your class. If you have a T instance, you could access the constructor through the property constructor but there’s probably a better way to do whatever it is you’re trying to do.

2 answers

0

With the desired syntax it is not possible, as the types generics in Typescript are just an abstraction about the type Any to facilitate inference about properties, parameters and method returns.

The closest thing to what you want, and what the language allows you to do, is to create a Genéric Factory that unlike a Class Factory the creation of objects of a certain type is no longer delegated to a subclass but to a generic type.

In the documentation typescript is written:

When creating Factories using generics, it is necessary to refer to class types by their construction functions.

function create<T>(c: {new(): T; }): T {
    return new c();
}

Example:

interface IClasse{
  printName():void;
}

class Classe1 implements IClasse{
  printName(){
    console.log("Sou a classe1");
  }
}

class Classe2 implements IClasse{
  printName(){
    console.log("Sou a classe2");
  }
}

class Classe3 implements IClasse{
  printName(){
    console.log("Sou a classe3");
  }
}

class Generic<T extends IClasse> {

  //Class factory genérico
  static factory<T>(arg:{new():T}):T{
    return new arg();
  }

}

//Usa o factory para criar algumas instâncias
//e em cada instância criada chama o método printName()
Generic.factory(Classe1).printName();
Generic.factory(Classe2).printName();
Generic.factory(Classe3).printName();

Which results in:

Sou a classe1
Sou a classe2
Sou a classe3

Repl.it of the example:

0

You can use this concept of Generics in typescript in newer versions, a simple example:

class Generic<T> {
    constructor(arg: T) {
        console.log(`Valor: ${arg}, Tipo: ${typeof arg}`);
    }
}

function main() {
    new Generic<String>('Teste');    
}

main();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.