【问题标题】:Visual Studio Code JSON object losing intellisense in new functionVisual Studio Code JSON 对象在新函数中失去智能感知
【发布时间】:2019-01-20 14:50:47
【问题描述】:
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 配置不当还是什么?

【问题讨论】:

  • 除了second_function中的json之外的其他东西都可以传入; Intellisense 是一种最佳猜测,但它不会运行您文件中的代码来尝试猜测您将来可能会做什么。
  • 仅仅因为您将变量命名为与函数参数(json)相同的名称(json),并不意味着VSCode可以推断出函数参数的类型。尝试在代码中使用 js-doc 来提示类型 github.com/Microsoft/TypeScript/wiki/…

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


【解决方案1】:

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

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

完成这项工作的方法是这样......

/**
 * 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!
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-07
    • 2016-04-12
    • 2018-02-24
    • 2016-06-27
    • 2016-02-27
    • 2017-05-28
    • 1970-01-01
    • 2015-05-03
    相关资源
    最近更新 更多