Closure Compiler warns “Bad type annotation. Unkno

2019-07-18 23:06发布

问题:

I'm getting a warning for every Ecmascript 6 class that inherits from another class when compiling with Closure Compiler:

I've dumbed things down as much as possible and still get the warning:

/src/main/js/com/tm/dev/Dog.js: WARNING - Bad type annotation. Unknown type module$$src$main$js$com$tm$dev$Animal.default

The compiled code does run correctly. (I've tried a number of annotations which only made things worse.) Anyone know what's expected here?

Animal.js:

export default class{
    constructor(){
        this.legs = [];
    }
    addLeg(legId){
        this.legs.push( legId );
    }
}

Dog.js:

import Animal from './Animal';

export default class extends Animal {
    constructor(){
        super();
        [1,2,3,4].forEach(leg=>this.addLeg(leg));
        console.log( 'Legs: ' + this.legs.toString() );
    }
}

回答1:

A hint is in the warning message, though it would obviously be confusing if you're not familiar with Closure Compiler's annotation inspection.

The Closure Compiler can use data type information about JavaScript variables to provide enhanced optimization and warnings. JavaScript, however, has no way to declare types.

Because JavaScript has no syntax for declaring the type of a variable, you must use comments in the code to specify the data type.

(The following is untested.)

Closure Compiler is reporting that in Dog.js it does not recognise the "type" Animal. This is because you are exporting an unnamed class expression: export default class.

So you could give your class a name (export default class Animal) and Closure Compiler may recognise the token Animal when it is consumed in Dog.js.

And you can also give your class a JSDoc that marks it as a @constructor:

/**
 * Animal.
 * @constructor
 */
export default class Animal {}