Closure Compiler warns “Bad type annotation. Unknown type …” when Ecmascript 6 class is extended

馋奶兔 提交于 2019-12-11 00:33:34

问题


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 {}


来源:https://stackoverflow.com/questions/37577183/closure-compiler-warns-bad-type-annotation-unknown-type-when-ecmascript-6-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!