Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Closure: How to annotate a parameter used as a constructor

I use require.js for dependency management and Google Closure annotations to empower me with autocompletion (in WebStorm / IDEA). We rely heavily on Backbone and develop our Javascript code in Java-like fashion - i.e. both with static and instance methods.

What remains elusive is how to properly write annotations for function arguments that are in fact classes - parameters used together with new keyword.

require(['foo'], function(Foo) {
  var bar = new Foo();
});

WebStorm and/or Google Closure correctly assume it is an instance of Foo if I annotate the parameter as follows:

require(['foo'],
/** @param {Foo} Foo */ 
function(Foo) {
   Foo.<cursor> <-- gives me an autocompletion for an instance of Foo
});

A quick googling suggests using function(new: Foo) as a parameter description. This approach, however, loses autocompletion for constructor parameters and/or possible static methods the class has.

The construct I hope for should resemble this one:

require(['foo'],
/** @param {Type<Foo>} Foo */
function(Foo) {
   Foo.<cursor> <-- gives me an autocompletion for statics of Foo
});

Is there a way to achieve this?

like image 894
Maros Urbanec Avatar asked Mar 23 '23 22:03

Maros Urbanec


1 Answers

You're looking for

/** @param {function(new: Foo)} someConstructor */

You can also specify the arguments of the constructor, by doing something like

function(new: Foo, ArgType1, ArgType2)

The relevant passage from the docs:

Operator Name: Function new Type:

Syntax Example: {function(new:goog.ui.Menu, string)}

A function that takes one parameter (a string), and creates a new instance of goog.ui.Menu when called with the 'new' keyword.

Specifies the constructed type of a constructor.

like image 146
domenico Avatar answered Apr 05 '23 21:04

domenico