Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSDoc: how to document a function that returns an instance of a passed constructor?

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

like image 810
mvlabat Avatar asked Jul 02 '18 11:07

mvlabat


1 Answers

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

like image 126
Candice Canoso Avatar answered Nov 14 '22 21:11

Candice Canoso