Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating generic classes and functions in javascript ES06

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?

like image 825
Rahul Rastogi Avatar asked Dec 02 '22 11:12

Rahul Rastogi


2 Answers

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.

like image 156
Amit Avatar answered Dec 05 '22 18:12

Amit


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();
like image 42
Andrey Avatar answered Dec 05 '22 18:12

Andrey