Using Class Types in Generics in TypeScript

Classes can also be used as a generic type. You just need to specify the class type using its constructor. Therefore, instead of the parameter type:T, we need to specify type: {new(): T;}. Let's make a function that will in turn create a new user from the class User:

typescriptfunction getUser <T> (type: { new (): T; }): T {
  return new type();
}

class User {
  constructor() {
    console.log('You create a new user!');
  }
}

let user: User = getUser(User);

The result of the executed code:

typescript'You create a new user!'