简体   繁体   中英

Closure linter warning about interfaces

I'm using the closure compiler and I have two classes that I would like to assert have a minimum set of methods/properties. To accomplish this, I've created an interface ... eg:

goog.scope(function() {



/**
 * @interface
 */
namespace.Foo = function() {};
var Foo = namespace.Foo


/**
 * @return {string}
 */
Foo.prototype.bar = function() {};

});  // goog.scope

The problem is that Foo.prototype.bar doesn't have a return statement, so the closure linter complains even though closure itself is completely happy.

Line 38, E:0218: Found @return JsDoc on function that returns nothing
Line 56, E:0218: Found @return JsDoc on function that returns nothing

Of course, if I remove the @return annotations then closure is unhappy and throws warnings about overriding a method and returning something incompatible with the interface. I don't want to disable this warning because that's pretty much the reason why I wrote the interface in the first place (to make sure that all of the implementors are doing what they need to do).

Is there any magical incantation that I can use to disable that warning in the closure linter just in this file?

It turns out that the answer was just waiting to be discovered in the closure-linter source code/test cases :

They write something like:

/**
 * Sample interface to demonstrate correct style.
 * @interface
 */
sample.GoodInterface = function() {
};


/**
 * Legal methods can take parameters and have a return type.
 * @param {string} param1 First parameter.
 * @param {Object} param2 Second parameter.
 * @return {number} Some return value.
 */
sample.GoodInterface.prototype.legalMethod = function(param1, param2) {
};

which apparently lints fine in their test cases. How is that different from mine? Well, they didn't use goog.scope to do any aliasing. When I removed the aliasing (eg

/**
 * @return {string}
 */
namespace.Foo.prototype.bar = function() {};

the closure-linter is now smart enough to figure out that Foo is part of an interface and it doesn't require any implementation in the methods. Awesome.

Try the following:

/**
 * @return {string}
 */
namespace.Foo.prototype.bar;

Interfaces don't need any function body at all. I suspect they are only visible to the compiler and don't even wind up in your code at all.

Or, because you are using goog.scope you can write:

/**
 * @return {string}
 */
Foo.prototype.bar;

You may try @abstract tag, this may help. If not, closure complier can suppress warnings. I think something like this will work.

/**
 * @return {string}
 * @suppress {missingReturn}
 */
 Foo.prototype.bar = function() {};

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM