How to fight a lots of unresolved variables warnin

2019-01-12 23:45发布

Ok, I have a function which takes a data from ajax:

function getData(data){
    console.log(data.some_unres_var);
}

Webstorm says that some_unres_var - is unresolved variable. I don't know what to do with lots of such warnings.

I see few options:

  • suppress warnings;
  • add a json source file with fields (more details);
  • use arrays-like syntax: data['some_unres_var'] (but jslint warn me to didn't do this);
  • ???

Also Webstorm offering me to create namespace for the "data" (add an annotation like /** @namespace data.some_unres_var*/), create such field, or rename it.

4条回答
Emotional °昔
2楼-- · 2019-01-13 00:12

Use JSDoc:

/**
 * @param {{some_unres_var:string}} data
 */
function getData(data){
    console.log(data.some_unres_var);
}
查看更多
We Are One
3楼-- · 2019-01-13 00:14

JSDoc the object. Then its members.

/**
 * @param data          Information about the object.
 * @param data.member   Information about the object's members.
 */
function getData(data){
    console.log(data.member);
}
  • @property for local variables (non parameters)
  • Tested in PyCharm. @Nicholi confirms it works in Webstorm.
  • The {{ member:type }} syntax Andreas suggested may conflict with Django templates.
  • Thanks to Jonny Buchanan's answer citing the @param wiki.

To document arrays of objects, use [] brackets as JSDoc suggests:

/**
 * @param data
 * @param data.array_member[].foo
 */
查看更多
smile是对你的礼貌
4楼-- · 2019-01-13 00:17

using a dummy js file with anonymous function expression returning the json literal, as written at http://devnet.jetbrains.com/message/5366907, may be a solution. I can also suggest creating a fake variable that will hold this json value, and use this var as a value of @param annotation to let WebStorm know what the actual type is. Like:

var jsontext = {"some_unres_var":"val"};
/** @param {jsontext} data
function getData(data){
    console.log(data.some_unres_var);
}

See also http://devnet.jetbrains.com/message/5504337#5504337

查看更多
Anthone
5楼-- · 2019-01-13 00:20

All other answers are incorrect for the general case. What if you don't get data as a parameter? You don't have JSDoc then:

function niceApiCall(parameters) {
  const result = await ...  // HTTP call to the API here
  for (const e of result.entries) {
    .. // decorate each entry in the result
  }
  return result;
}

WebStorm will warn that "result.entries" is an unresolved variable (field).

The general solution is to add an @namespace declaration:

function niceApiCall(parameters) {
  /** @namespace result.entries **/
  const result = await ...  // HTTP call to the API here
  for (const e of result.entries) {
    .. // decorate each entry in the result
  }
  return result;
}
查看更多
登录 后发表回答