0

This is similar to question 38702398, but I have an additional requirement.

I want PhpStorm to stop pestering me with the "Possible iteration over custom/inherited properties" diagnostic.

In order to achieve this, I want to find a way to use JSDoc to inform PhpStorm that the object being iterated is a "plain" object and doesn't have any custom or inherited properties. I am not as much interested in documenting the value type of this dictionary object as I am in successfully declaring to PhpStorm's built-in linter that the object is indeed a plain dictionary.

Consider this example:

class DictionaryEntry {

    // ...
}

/**
 * @typedef {Object.<string, DictionaryEntry>} Dictionary
 */

/**
 * @param {Dictionary} dictionary
 */
function use_dictionary(dictionary)
{
    for (let key in dictionary) {

        const entry = dictionary[key];         // <- get rid of diagnostic here!

        // do something with entry ...
    }
}

Is this something that ShouldWork™, i.e. a bug in PhpStorm?

LazyOne
  • 158,824
  • 45
  • 388
  • 391
Szczepan Hołyszewski
  • 2,707
  • 2
  • 25
  • 39
  • 1
    Even if the IDE used it in this way, this would no be a good idea because properties added to `Object.prototype` would still be discoverable. `hasOwnProperty` is often used as a guard here. However, if you don't need `key` but only need `entry`, nowadays, with ES6 (which you are already using with `class`), you can use `for...of` instead of `for...in` to iterate (`for (const entry of dictionary)`) which avoids the need for `key`. You may also be able to do `for (const [key, entry] of Object.entries(dictionary))` – Brett Zamir Jan 01 '21 at 23:38
  • Another alternative is using `Map` instead of a plain object. – Brett Zamir Jan 01 '21 at 23:39
  • Who in their right mind adds stuff to `Object.prototype`? – Szczepan Hołyszewski Jan 01 '21 at 23:47
  • They shouldn't, but in case some library one is using does so (or if one enjoys such footguns), this is why the warning exists. – Brett Zamir Jan 02 '21 at 03:04

0 Answers0