Вопрос

I cannot get to properly type the following piece of code:

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

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

I get the following warning:

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

How can I properly type this in this example?

-- EDIT --

If you want to see the warning, you need to set reportUnknownTypes to trueas explained here. I am trying to get to 100% typed code and I figured I could not reach that for that simple a program.

Это было полезно?

Решение

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

doesn't specify the "this" type so it is unknown. To specify it in that fashion you would want to use:

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

Using "@param {number}" lets the compiler infer the "this" type from the fact it was declared on F's prototype.

Другие советы

You seem to need to use @param {number} b instead of @type {function(number)}. Typing with @param doesn't throw the warning. Doesn't make a whole lot of sense, but it works:

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

--

Original answer:

I think it's because you didn't type a in your constructor. Try this:

/**                                                                                                                                                                                      
 * @constructor                                                                                                                                                                          
 */
function F() {

    /**
     * @type {number}
     * @private
     */
    this.a = 0;
};
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top