使用闭包编译器正确键入实例变量

Properly type instance variables with closure compiler

本文关键字:实例 变量 闭包 编译器      更新时间:2023-09-26

我无法正确键入以下代码:

/**                                                                                                                                                                                      
 * @constructor                                                                                                                                                                          
 */
function F() {
      this.a = 0;
};
/**                                                                                                                                                                                      
 * @type {function(number)}                                                                                                                                                              
 */
F.prototype.g = function(b) {
    this.a += b;
};

我收到以下警告:

test.js:12: WARNING - could not determine the type of this expression
    this.a += b;
    ^

在本例中,如何正确键入this

--编辑--

如果您想看到警告,您需要将reportUnknownTypes设置为true,如下所述。我正试图获得100%类型的代码,但我认为我无法通过这么简单的程序达到这一点。

/** @type {function(number)} */ 

没有指定"this"类型,因此它是未知的。要以您想要的方式指定它,请使用:

/** @type {function(this:F, number)}

使用"@param{number}",编译器可以根据在F的原型上声明的事实推断出"this"类型。

您似乎需要使用@param{number}b而不是@type{function(number)}。使用@param键入不会引发警告。没有什么意义,但它有效:

/**                                                                                                                                                                                      
 * @param {number} b                                                                                                                                                             
 */
F.prototype.g = function(b) {
    this.a += b;
};

--

原始答案:

我认为这是因为你没有在构造函数中键入。试试这个:

/**                                                                                                                                                                                      
 * @constructor                                                                                                                                                                          
 */
function F() {
    /**
     * @type {number}
     * @private
     */
    this.a = 0;
};