如何在Webstorm中对抗大量未解决的变量警告

问题描述 投票:96回答:4

好的,我有一个从ajax获取数据的函数:

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

Webstorm说some_unres_var是未解决的变量。我不知道如何处理这么多警告。

我看到几个选项:

  • 压制警告;
  • 添加带有字段的json源文件(更多details);
  • 使用类似数组的语法:data['some_unres_var'](但是jslint警告我不要这样做);
  • ???

Webstorm也让我为“数据”创建命名空间(添加像/** @namespace data.some_unres_var*/这样的注释),创建这样的字段或重命名它。

javascript coding-style webstorm
4个回答
91
投票

使用JSDoc:

/**
 * @param {{some_unres_var:string}} data
 */
function getData(data){
    console.log(data.some_unres_var);
}

39
投票

JSDoc对象。然后是其成员。

/**
 * @param data          Information about the object.
 * @param data.member   Information about the object's members.
 */
function getData(data){
    console.log(data.member);
}
  • @property用于局部变量(非参数)
  • 在PyCharm中测试过。 @Nicholi证实它适用于Webstorm。
  • Andreas建议的{{ member:type }}语法可能与Django模板冲突。
  • 感谢Johnny Buchanan的qazxsw poi引用了qazxsw poi。

要记录对象数组,请使用answer括号作为JSDoc @param wiki

[]

12
投票

所有其他答案对于一般情况都是不正确的。如果你没有将suggests作为参数怎么办?那你没有JSDoc:

/**
 * @param data
 * @param data.array_member[].foo
 */

WebStorm将警告“result.entries”是一个未解析的变量(字段)。

一般的解决方案是添加一个data声明:

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;
}

6
投票

使用带有匿名函数表达式的虚拟js文件返回json文字,如@namespace所写,可能是一个解决方案。我还建议创建一个保存此json值的伪变量,并将此var用作@param注释的值,以使WebStorm知道实际类型是什么。喜欢:

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;
}

另见http://devnet.jetbrains.com/message/5366907

© www.soinside.com 2019 - 2024. All rights reserved.