Search code examples
javascriptecmascript-6phpstormjsdoc

ES6 - How to declare implicit class member?


If class members created from some options, how to declare them?

class cls {

    constructor(options) {

        Object.assign(this, {
            arr: [],
        }, options);

        this.arr[0] = 1; // <- IDE thinks that arr is an unresolved variable
    }
}

Solution

  • In order for class property that wasn't explicitly defined to be recognized by IDE (Jetbrains PhpStorm/WebStorm), it's possible to specify a member with JSDoc:

    class cls {
        /**
         @name cls#arr
         @type Array
         */
    
        constructor(options) {...}
    }
    

    Since property assignment with Object.assign doesn't provide additional benefits, a more natural way is to explicitly define a property explicitly on this (as other answers mention).

    In ES6:

    class cls {
       constructor(options) {
            this.arr = [];
    
            Object.assign(this, options);
    
            this.arr[0] = 1;
        }
    }
    

    In ES.next with class field proposal, requires stage 3 (or lower) preset in Babel:

    class cls {
       arr = [];
    
       constructor(options) {
            Object.assign(this, options);
    
            this.arr[0] = 1;
        }
    }
    

    Class fields are evaluated before constructor body, ES.next option is syntactic sugar for ES6 option. These two options are identical and recognized by IDE.