Visual Studio Code JSON对象在新功能中失去了智能意识

时间:2018-08-13 19:55:22

标签: javascript json configuration visual-studio-code javascript-intellisense

function first_function() {
  var json = { a: 0, b: 1 };
  second_function(json);
}

function second_function(json) {
  // Pressing ctrl+enter to start intellisense
  json.[ctrl+enter] // No intellisense, properties a and b won't show
}

嘿,所以我注意到Visual Studio Code中有一个具有JavaScript函数的怪异事物,例如在我的示例中的 first_function ,其中创建了一个JSON变量并将其传递给 second_function

问题:在第二个函数中,当我尝试启动JSON的智能感知时,没有显示属性 a和b 。发生了什么,有什么事情可以解决?我的VSC配置不正确吗?

1 个答案:

答案 0 :(得分:0)

  

仅因为您给变量命名的名称与函数参数(json)相同,并不意味着VSCode可以推断出函数参数的类型。尝试在代码中使用js-doc来提示类型https://github.com/Microsoft/TypeScript/wiki/JsDoc-support-in-JavaScript-mpm

此答案非常感谢!但是,该解决方案不切实际且冗长。这是Google Apps脚本(GAS)中带有ECMAScript 5(ES5)的项目,并且使用Visual Studio Code进行编辑和类型检查。

完成这项工作的方式就是这样...

/**
 * This long note to get intellisense for an object
 * @param {Object} json
 * @param {Number} json.a
 * @param {Number} json.b
 */
function second_function(json) {
  json.[Start Intellisense] //A AND B ARE THERE YAY
}

作为一种解决方案,因为Google Apps脚本是如此愚蠢,所以我最终用所需的对象制作了var构造函数。 GAS不一定必须创建一个类,因为使用var json = {}然后为此编写一个很长的JSDoc根本不值得付出努力。

这更实用

/**
 * Sets up the record I want to build
 * @param {Array} input
 */
function Json2Construct(input) {
  /** @type Number */
  this.a = input[0];
  /** @type Number */
  this.b = input[1];
};

/**
 * Creates the record and sends to next function
 */
function first_function() {
  var input = [0, 1];
  var json = new Json2Construct(input);
  second_function(json);
}

/**
 * Will have intellisense this time too
 * @param {Json2Construct} json
 */
function second_function(json) {
  json.[Start Intellisense] // Woo a and b are also there!
}

我非常感谢您的帮助,非常感谢!