10

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?

1
  • 4
    such syntax does not exist in javascript - so - no (since javascript isn't strictly typed, it would make little sense) (try "typescript" if you wnat strictly typed javascript) typescriptlang.org/docs/handbook/generics.html ... or haxe Commented Nov 14, 2017 at 5:17

5 Answers 5

13

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();
Sign up to request clarification or add additional context in comments.

4 Comments

I like this! Why not?
It's not working when field is an Array<T>.
not sure where did you find Array<T> in JS, because that is syntax of typescript. class DerivedFromGeneric extends GenericClass(Array, BaseClass) works
Андрей, ты спас мой день!
11

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.

2 Comments

Currently I'm using "Flow" for type-checking. Can I use TypeScript with Flow?
@RahulRastogi I don't think so. I have not used Flow but I think both are competitors, You use one or another. Try flow.org/en/docs/types/generics
6

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
}

1 Comment

Just rememeber that type information is not available after code is compiled into JS - so it is quite different from Java.
3

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.

1 Comment

I've type-checking support using "Flow".
2

You can use Typescript for this purpose.

https://www.typescriptlang.org/docs/handbook/generics.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.