I'm from java background. I use Generics in java in following way:
  class ApiResponse<T> {
    T data;
    T getData(){
      return T;
    }
  }
I'm unable to use generics in javascript ES06. I wanna know whether it's possible or not creating generic classes?
JavaScript is a dynamically typed language and it doesn't have any generics. You can write a normal function/method, it will work for all types.
P.S. Use Typescript if want to code like you do in Java.
How do you like this, Elon Musk? Pure js, no typeflow/typescript
class BaseClass {
    hello = function () {
        console.log('hello!');
    }
}
function GenericClass(T, Base) {
    return class extends Base {
        field = new T();
    }
}
class DerivedFromGeneric extends GenericClass(String, BaseClass) {
    greet = function() {
        this.hello();
        console.log('greetings ', this.field);
    }
}
let i = new DerivedFromGeneric();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With