10

For instance, I have the following function:

function createInstanceOf(ObjectConstructor) {
  return new ObjectConstructor;
}

I want to make WebStorm autocompletion working when I pass a class as an argument. For example: if I call createInstanceOf(ClassA) I want to see autocompletion for ClassA instance, if I call createInstanceOf(ClassB) – for ClassB instance. So JSDoc function has to be generic.

It's easy to define a generic function with JSDoc and make @return value type be the same as @param, but I've found no way to treat @param type as a constructor for returned object.

So this doesn't work:

/**
 * @param {T} ObjectConstructor
 * @returns {T}
 * @template T
 */
function createInstanceOf(ObjectConstructor) {
  return new ObjectConstructor;
}

I also tried to make it working this way:

/**
 * @param {function(new:T)} ObjectConstructor
 * @returns {T}
 * @template T
 */
function createInstanceOf(ObjectConstructor) {
  return new ObjectConstructor;
}

But maybe I use closure types wrong, or WebStorm can't resolve such generic types.

If there're several solutions for JSDoc, I'd like to find out which ones work specifically with WebStorm IDE autocompletion.

Thank you

mvlabat
  • 577
  • 4
  • 17
  • [This question](https://stackoverflow.com/questions/16017627/document-generic-type-parameters-in-jsdoc) might help. – user7637745 Jul 02 '18 at 12:46
  • 1
    @RichardSzakacs, thanks for the suggestion. I've already tried closure types suggested in the answers. Updated my question: added one more not working example of what I've come up with – mvlabat Jul 02 '18 at 12:58
  • 1
    You're welcome! I just deleted my original answer, since I'm looking for this feature myself too, but apparently at the moment only Google Closure supports the `@template`, JSDoc doesn't have any documentation about it and I'm not able to tell, when are we gonna get a working solution for this feature. But I'm hoping... – user7637745 Jul 02 '18 at 13:01
  • I would also be interested in a better approach... currently I'm just working around using something like `/** @type {SomeType} */ const instance = createInstanceOf(SomeType);` everywhere I'm using such a method – Ovidiu Dolha Apr 25 '20 at 13:46

1 Answers1

11

You probably don't need this anymore, but I too have been stuck on this for months so for other people wondering, you can do it like this:

/**
 * @template T
 * @param {new() => T} ObjectConstructor
 * @returns {T}
 */
function createInstanceOf(ObjectConstructor) {
  return new ObjectConstructor;
}

Got the answer from this article

Candice Canoso
  • 111
  • 1
  • 5