Creating generic classes and functions in javascript ES06

Viewed 18489

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?

5 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.

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();

Javascript in itself doesn't provide any syntax to support generic classes. But it's possible using:

Flow

or

Typescript

Let me show an example of using generic class using Flow in javascript ES06:

export class ApiResponse<T> {

    data: ?T = null
}

Javascript doesn't have strict typing so there is no need for Generics because all variables can be assigned to any type at any time.

Related